GNUPLOT

- not so Frequently Asked Questions -

update 2004/11/29

Recursive Definition

You can define a function recursively, so that you can include your defined function in itself. For example, a factorial of integer number N!=FAC(N) is written as FAC(N)=N*FAC(N-1), you can define this in gnuplot as:

gnuplot> fac(n) = n * fac(n-1)

This one-line function is infinite-loop in which the variable N decreases by 1. In order to terminate the loop, we use a ternary operator. The next example tells gnuplot to stop the loop when N=0.

gnuplot> fac(n) = (n==0) ? 1 : n * fac(n-1)

This means, when N is equal to zero, just after the '?' is evaluated, otherwise fac(n-1) is executed, and again, the same function is called but its argument is n-1. The function-call is terminated when its argument is zero.

To calculate N!, N should be integer. When the argument is a real number, we use a gnuplot function int() to make it integer. Perhaps you also need to include the restriction that N must be positive, although we don't consider this.

gnuplot> fac(x) = (int(x)==0) ? 1.0 : int(x) * fac(int(x)-1.0)

Now you can calculate the function fac(x), as follows:

gnuplot> fac(x) = (int(x)==0) ? 1.0 : int(x) * fac(int(x)-1.0)
gnuplot> print fact(1)
1.0
gnuplot> print fact(5)
120.0
gnuplot> print fact(5.5)
120.0
gnuplot> print fact(20)
2.43290200817664e+18

It is known that N! can be approximated by the Stirling formula.

eq

Let's compare the Stirling formula with our function fac(x).

gnuplot> stirling(x) = sqrt(2*pi*x) * x**x * exp(-x)
gnuplot> set xrange [1:15]
gnuplot> set yrange [1:1e+10]
gnuplot> set log y
gnuplot> set sample 15
gnuplot> plot stirling(x) notitle with lines,\
>             fact(x)     notitle with points
fact
up