![]() |
Intro to Scientific ComputingPHYS 27/193Physics Department University of the Pacific |
As you know we can plot all kinds of mathematical functions (see Builtin Functions) with gnuplot. However, an important class of functions are ones that we can make up ourselves out of other functions.
If gnuplot is not already running,
We already learned how to use gnuplot as a calculator to define our own variables, as you did in HW 5 where you calculated the power output of the sun. There, you defined constants made of numbers and builtin constants, such as
gnuplot> T = 5.5e3 # set temp. of sun's surface gnuplot> r = 7e8 # solar radius gnuplot> A = 4 * pi * r**2 # surface area gnuplot> print A 6.15752160103599e+018 # in m**2 gnuplot> P = flux * T**4 * A # solar power output gnuplot> print P 3.27/19391028086952e+026 # in watts |
Try this:
gnuplot> |
You can also define a function of several variables:
gnuplot> |
You can use functions in other functions
gnuplot> |
You can build quite complicated functions with gnuplot. Remember however, that the variable that is uses for plotting in a 2-D plot is always x.
One very useful construct that I sometimes use is the C programming if/then short hand notation which gnuplot recognizes:
The
x == 0 # is x equal to zero? x != 0 # is x NOT equal to zero? X > 4 || x < 3 # is x greater than 4 OR less than 3? x >= 0 && x <= y # is x greater to or equal to zero AND less than or equal to y?where we have used the C programming logical conditions: ==, !=, >, <, >=, <=, &&, and ||. The last two, if you haven't figured them out already, are &&, meaning logical AND (both things must be true), and || meaning logical OR (one or the other can be true).
If the question part is TRUE, the result is the thing between the ? and : If the question is FALSE, the result is the thing after the :
Here's an example. Plot a function whose value is f(x) = 50 if x is between 0 and 1, but f(x) = 0 otherwise.
gnuplot> |
You can even define functions
gnuplot> |
One last thing. Notice that I can define a function with a variable, c, in it:
gnuplot> |
However when I try to plot the function, gnuplot complains that the variable c is not defined, hence it, rightly, doesn't know how to plot the function.
If I go ahead and define c
gnuplot> |
gnuplot can now plot the function, since it knows how to evaluate it. I can
update the value of c by typing
Notice too in your plot that gnuplot stopped plotting for x <= 1, since the function is complex there (in fact it's singular at x = -1). It will however, still tell you the complex value if you ask:
gnuplot> |
Next, we'll use the ability to define functions with constants to let gnuplot find the "Best" function that fits our data.
Next: Fitting Functions to Data