Sunday, September 30, 2012

Gnuplot example: Math Invaders - Remember Space Invaders and Galaxian?



This is a parameter animation (plotted upside down) for the modified Thomae function:



gnuplot script:

d = 0.001
m = 250
f(n,k,x) = k > m ? 3.2 : ( abs(k*x - int(k*x)) < d ? \
3.2-(1+0.1*n*n)/(k*k-abs(k*x)) : f(n,k+1,x) )
set xrange [-1.6:1.6]
set yrange [0:3.2]
set size ratio -1
set samples 10000
unset key
unset xtics
unset ytics
unset border
set bmargin 0
set lmargin 0
set rmargin 0
set tmargin 0
set term gif size 400, 400 animate background rgb "black"
set output "C:\math_invaders.gif"
set pointsize 0.5
do for [i=0:150]{
  plot f(i,1,sin(x)) with points pt 11 lc rgb "white"
}
set output


Note that we set less samples(10000). By incresing samples to 200000,
we can obtain a more accurate (but less fun) picture.



( Mathematical software used: gnuplot )


Related posts:

Tuesday, September 25, 2012

Gnuplot examples: plotting functions defined on rational numbers

Consider the Thomae function (or modified Dirichlet function):


This function is continuous at all irrational numbers and discontinuous at all rational numbers.

We will define f approximately as a gnuplot function (see f(1,x) below) such that we can plot
the graph of y = f(sin(x)) directly.



1. y = f(sin(x)) with linespoints
(Click on the image for a larger view.)

Script 1:
d = 0.001
m = 250
f(k,x) = k>m ? 0 : (abs(k*x-int(k*x))<d ? 1.0/k : f(k+1,x))
set xrange [-pi:pi]
set yrange [-0.5:1.5]
set samples 100000
set size ratio -1
unset key
set pointsize 0.25
plot f(1,sin(x)) with linespoints ls 7 lw 0.25 lc rgb "red"



2. y = f(sin(x)) with points
(Click on the image for a larger view.)

Script 2:
d = 0.001
m = 250
f(k,x) = k>m ? 0 : (abs(k*x-int(k*x))<d ? 1.0/k : f(k+1,x))
set xrange [-pi:pi]
set yrange [-0.5:1.5]
set samples 100000
set size ratio -1
unset key
set pointsize 0.1
plot f(1,sin(x)) with points pt 7 lc rgb "#00cc00"



3. y = f(sin(x)) with dots
(Click on the image for a larger view.)

Script 3:
d = 0.001
m = 250
f(k,x) = k>m ? 0 : (abs(k*x-int(k*x))<d ? 1.0/k : f(k+1,x))
set xrange [-pi:pi]
set yrange [-0.5:1.5]
set samples 100000
set size ratio -1
unset key
plot f(1,sin(x)) with dots lc rgb "black"



4. Golden Ring (parametric plot)
(Click on the image for a larger view.)

Script 4:
d = 0.001
m = 250
f(k,x) = k>m ? 0 : (abs(k*x-int(k*x))<d ? 1.0/k : f(k+1,x))
set xrange [-1.3:1.3]
set yrange [-1.05:1.55]
set size ratio -1
set samples 100000
set parametric
unset key
unset xtics
unset ytics
unset border
set term svg size 800, 800
set bmargin 1
set lmargin 1
set rmargin 1
set tmargin 1
set output 'C:\golden_ring.svg'
set pointsize 0.125
set multiplot
plot [0:2*pi] -f(1,sin(t))*sin(t), 1+f(1,sin(t))*cos(t) \
w p pt 7 lc rgb "#ffd700"
plot [0:2*pi] -(f(1,sin(t))*sin(t)+sin(2*t)), \
f(1,sin(t))*cos(t)+cos(2*t) w p pt 7 lc rgb "#ffd700"