Nugroho's blog.: Python
Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Monday, June 5, 2017

Using Kivy on MacOS


Here's my first kivy program after a while.



Wednesday, May 10, 2017

Animation using Matplotlib

Suppossed we want to animate our plot, say f(x) = (x-c)^(2) to see the effect of various c value, we could do it in Python using Matplotlib module.

As we could see at the code below that the animation part is in

ani =  animation.FuncAnimation(fig, animate, np.arange(-10,10), interval =  25, blit=False)

What about our own def? We could call it inside animate and use variable i (defined in ani, the np.arange(-10,10) part) to whatever treatment on our self define function f(x). In this case, I use i as c parameter value. I like the result, :)

Sunday, May 7, 2017

What About Unbounded End?


Yeah, what about it? The previous code have the both end bounded.

If we want a free/unbound end, we could set the condition at the with this properties (or we could choose whatever we like)

dy/dx=0

So we will have

y[1]-y[0]=0
y[0] = y[1]

if we want both free ends, we could set the other end as well

y[n] = y[n-1]

So, we just have to modify the original just a bit.

Beware though, with both ends free, we could lost the strings, :)

Saturday, May 6, 2017

Waves Equation Animation in Python

I use matplotlib module to do the animation.

The main code is in def waves(y0,y1,cb) that use finite difference that solved initial value problem and boundary value problem simultaneously.    

code
from pylab import *
import matplotlib.animation as animation

fig,ax = subplots()

def waves(y0,y1,cb):
    y2 = y0
    for i in range(1,len(y0)-1):
        y2[i] = 2*y1[i]-y0[i]+cb*(y1[i+1]-2*y1[i]+y1[i-1])
    return y2

x   = linspace(0.,1.,20)
dx  = 1./(len(x))
y0  = sin(2*pi*x)
vy0 = 12.

b   = 1./32.  #dt2/dx2
dt  = sqrt(b*dx*dx)
print dt

c   = 1.

cb  = c*b

y1  = y0 + vy0*dt

print y0
print y1

line,   = ax.plot(x,y0)
def animate(i):
    global y0,y1,cb
    y2  = waves(y0,y1,cb)
    y0  = y1
    y1  = y2
    line.set_ydata(y0)
    return line,


#plot (x,y0)

ani =  animation.FuncAnimation(fig, animate, np.arange(1,200), interval =  25, blit=False)

grid(True)
ylim(-10,10)
show()


.

Tuesday, May 2, 2017

Gauss Jordan in Python.


Yeah, it's basically Gauss elimination (or we could call it Gauss Naif :) ) but with slight modification at the end.

So, instead using back substitutions after zeroing the lower triangle, we straight on and zeroing upper triangle as well. As addition, we could normalize the diagonal elements so we have identity matrice.

And all is well, :)



Thursday, April 27, 2017

Gauss Naif in Python

Okay, we've done the manual one, how about automatize it?

It's actually just a matter of finding the pattern on that code and after we found the loop, we just have to well... loop it, :)



Wednesday, April 26, 2017

Manual Gauss Jordan in Python.

What if we didn't do back substitution on Gauss Naif method but eliminate the rest instead? Nah, we get the Gauss Jordan here.

The idea is after we do operation to make the  lower-triangle have zero value,  we continue the operation until all the component in the upper-triangle have zero value too, and the diagonal have value of one.

Basically, the matrix becomes identity matrix. This way, we didn't need subtitution at all since all variables already has the exact value on the right side, :)

Tuesday, April 25, 2017

Manual Gauss Naif Elimination using Python

How about some manual matrix using manual Gauss just like always, but in Python? Okay, here it is.

I use tuple, I think it's just the same as array for this purpose.

I created matrix a with random value.  It's like linear equation system; three unknown variables with three equation. The purpose of this code is to find x1, x2 and x3.

Oh, in this case, its x0, x1 and x2, :)

Monday, April 24, 2017

That's Not Fair!


Maybe that's something come to our mind when we read this code. Yeah, that's forward dfference. It's designed to get the difference value using the point we calculate and the next one. That means the value will "lopsided" by nature, :)



Friday, April 21, 2017

Searching Multiple Roots Numerically.

This Python code only works with function that crossing x-axis.

The idea is we started from x=0 and walking to the positive direction and evaluating f(x) as we walk.

If there's change of the sign of f(x) from + to -, or vice versa, there must be a root in that area.

We began to surround it to find the-x that correspond to f(x)=0. That x value is the root.

After the root is found, we began to walk along x-axis again until found any sign change of f(x), or until x limit set on code.

Wednesday, April 19, 2017

Lagrange Polynomial Interpolation on Python.


It's a whole a lot easier than Newton's divided differences interpolation polynomial, because there is no divided difference part that need a recursive function.



Sunday, April 16, 2017

Differentiation

We may already knew that on computational physic,  differentiation is used in Euler method to compute integration, or used in finite different method.

How about slope of the function? How do we use differentiation to differentiate a function?

If we have y = f(x), we will have slope value on, say, (x0 , f(x(0)) by differentiate it.

m = dy/dx = df(x)/dx.



For slope on x0, just compute it.

We could plot the linear function that have form

y = m x + c

Friday, April 14, 2017

Numeric Integration using Python and Pylab

Pylab is Python module that contain NumPy and MatPlotlib.

Let f(x) = x^2 and we want to integrate it from 0 to 1.

Numerically we could use square method or trapezoidal (which is almost better).


Thursday, April 13, 2017

Flappy Bird Like in Delphi

Remember the infamous Flappy Bird? Yup, I will create the program based on that algorithm.



Wednesday, April 12, 2017

Newton Polynomial in Python

I wrote code for this in Delphi. This time I want to rewrite it in Python based on this wiki.

I use this set of data point
(0,0)
(1,1)
(2,4)
(4,16)
(5,25)

and I use xc=3 for the test data.

It's obvious that these sets of data points have quadratic form and f(xc) must have value of 9.




The heart of code lay on this




def n(j,xc,x):
n = 1
for i in arange(j):
n *= (xc-x[i])

return n
def a(j,l,x,y):
if j==0:
return y[0]
elif j-l==1 :
return (y[j]-y[l])/(x[j]-x[l])
else:
return (a(j,l+1,x,y)-a(j-1,l,x,y))/(x[j]-x[l])


def N(xc,x,y):
N = 0
for j in range(len(x)):
N += a(j,0,x,y)*n(j,xc,x)

return N


Look at the function a(j,l,x,y), that's recursive function to obtain Newton divided difference value.

the whole code is this
from pylab import *

def n(j,xc,x):
n = 1
for i in arange(j):
n *= (xc-x[i])

return n
def a(j,l,x,y):
if j==0:
return y[0]
elif j-l==1 :
return (y[j]-y[l])/(x[j]-x[l])
else:
return (a(j,l+1,x,y)-a(j-1,l,x,y))/(x[j]-x[l])


def N(xc,x,y):
N = 0
for j in range(len(x)):
N += a(j,0,x,y)*n(j,xc,x)

return N

x = []
y = []
#initial value
x.append(0)
x.append(1)
x.append(2)
x.append(4)
x.append(5)

y.append(0)
y.append(1)
y.append(4)
y.append(16)
y.append(25)

#for testing
xc = 3

yc = N(xc,x,y)

print ''
print xc, yc
#plot
t = linspace(-7,7,100)
u = N(t,x,y)
plot(t,u)
grid(True)
show()



.


here's the graphics


with another sets of data points, I have another result
(0,0)
(1,1)
(2,4)
(4,16)
(5,25)




Monday, April 10, 2017

Another Turtle in Circle

There's always another way to solve something.

So, I have another code for "Turtle in Circle" code, :)

In the script below, I use turtle position to determine if it's still inside circle or not. If it outside circle, instead of send it to zero position, I send it to random position inside circle.

import turtle
from random import uniform
import numpy as np

turtle.shape("turtle")
#turtle.speed(1)
x = 0
y = 0
rmax=40

for i in range (1,1000):
a = uniform (-90,90) #angle
turtle.left(a)
d = uniform (-75,75) #distance
x = turtle.xcor()+d*np.cos(a*np.pi/180)
y = turtle.ycor()+d*np.sin(a*np.pi/180)
r = np.sqrt(x*x+y*y)
if r>rmax:
turtle.setx(uniform(-rmax,rmax))
turtle.sety(uniform(-rmax,rmax))
x = 0
y = 0
else:
turtle.forward(d)

turtle.exitonclick()





.

Sunday, April 9, 2017

Turtle in Circle


I use previous code and improve it so the turtle could only move at certain circle area.

import turtle
from random import uniform
import numpy as np

turtle.shape("turtle")
#turtle.speed(1)
x = 0
y = 0

for i in range (1,1000):
a = uniform (-90,90) #angle
turtle.left(a)
d = uniform (-75,75) #distance
x += d*np.cos(np.pi*a/180)
y += d*np.sin(np.pi*a/180)
r = np.sqrt(x*x+y*y)
if r>40:
turtle.setx(0)
turtle.sety(0)
x = 0
y = 0
turtle.forward(d)

turtle.exitonclick()





.



Saturday, April 8, 2017

Random Turtle Movement.


I use turtle module, the standard module, in Python.

The turtle movement has random direction (angle), and random distance (forward/backward).

import turtle
from random import uniform

turtle.shape("turtle")
turtle.speed(1)
for i in range (1,100):
#random angle
a = uniform (-90,90)
turtle.left(a)
#random move
d = uniform (-100,100)
turtle.forward(d)

turtle.exitonclick()






.



Thursday, June 2, 2016

Collision.





 Here's the Code
#code
from visual import *
from random import uniform

display(center=(0,2,0),background=(1,1,1), autoscale=False, range=4.5,
width=600, height=600, forward=(-.4,-.3,-1)) #arah kamera

distant_light(direction=(1,1,1), color=color.red)

Ball = sphere(radius=2, length=4, opacity=.3)

Bola = []
n = 5
for i in arange (n):
bola = sphere(color=color.green,radius=uniform(.2,.73))
bola.pos = vector(uniform(-1.5,1.5),uniform(-1.5,1.5),uniform(-1.5,1.5))
bola.v = vector(uniform(-1,1),uniform(-1,1),uniform(-1,1))
Bola.append(bola)

dt = 1./16

def pantul():
global Bola
for bola in Bola:
r = bola.pos
v = bola.v
if mag(r)>=Ball.radius:
r = 1.9*norm(r)
vp = (dot(v,norm(r)))*norm(r)
vr = v-vp
v = vr - vp
bola.r = r
bola.v = v
for i in arange (n-1):
for j in range(i+1, n):
ri = Bola[i].pos
rj = Bola[j].pos
vi = Bola[i].v
vj = Bola[j].v
rc = rj-ri
if Bola[i].radius+Bola[j].radius>mag(rc):
vpi = dot(vi,norm(rc))*norm(rc)
vri = vi-vpi
vpj = -dot(vj,norm(rc))*norm(rc)
vrj = vj-vpj

vi = vpj+vri
vj = vpi+vrj

Bola[i].v = vi
Bola[i].v = vj

def proses():
for bola in Bola:
r = bola.pos
v = bola.v
a = vector(0,0,0)
v += a*dt
r += v*dt

bola.pos = r

pantul()

while 1:
rate(37)
proses()

.

Sunday, May 29, 2016

Bouncing Ball inside a Cone


  I use vector projection and rejection to calculate velocity after bouncing the side of cone, :)





#code
from visual import *
from random import uniform

display(center=(0,2,0),background=(1,1,1), autoscale=False, range=4.5,
width=600, height=600, forward=(-.4,-.3,-1)) #arah kamera

distant_light(direction=(1,1,1), color=color.red)

Cone = cone(pos = (0,0,0), axis=(0,5,0), radius = 3, opacity = .2)


bola = sphere(color=color.green,radius=.2)
bola.y = 1
bola.x = -1
bola.z = 1

v = vector(1,-1,0)
dt = 1./16
r = bola.pos
rc = Cone.radius
h = vector(Cone.axis)

def pantul():
global r,v
#tumbukan dengan lantai
if r.y<0:
r.y = 0
v.y *= -1

rp = vector(r.x,0,r.z)
hb = h.y - r.y
rmaks = hb/h.y*rc
c = h-rmaks*norm(rp) #vektor garis singgung
#selimut kerucut dengan bidang singgung
#tumbukan dengan selimut kerucut
if mag(rp)>rmaks:
rp = norm(rp)*rmaks
r = vector(rp.x,r.y,rp.z)
vp = dot(v,norm(c))*norm(c)
v = 2*vp-v
print v



def proses():
global r,v
a = vector(0,0,0)
v += a*dt
r += v*dt

bola.pos = r

pantul()

while 1:
rate(37)
proses()

.
323f (5) amp (1) android (12) apple (7) arduino (18) art (1) assembler (21) astina (4) ATTiny (23) blackberry (4) camera (3) canon (2) cerita (2) computer (106) crazyness (11) debian (1) delphi (39) diary (286) flash (8) fortran (6) freebsd (6) google apps script (8) guitar (2) HTML5 (10) IFTTT (7) Instagram (7) internet (12) iOS (5) iPad (6) iPhone (5) java (1) javascript (1) keynote (2) LaTeX (6) lazarus (1) linux (29) lion (15) mac (28) macbook air (8) macbook pro (3) macOS (1) Math (3) mathematica (1) maverick (6) mazda (4) microcontroler (35) mountain lion (2) music (37) netbook (1) nugnux (6) os x (36) php (1) Physicist (29) Picture (3) programming (189) Python (109) S2 (13) software (7) Soliloquy (125) Ubuntu (5) unix (4) Video (8) wayang (3) yosemite (3)