Nugroho's blog.: That's Not Fair!

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, :)





Here's the code for it

from pylab import *

def f(x):
    return (x*x)

def df(xc):
    m   = (f(xc+dx)-f(xc))/(dx)
    c   = f(xc) - m * xc
    
    return (m*x+c)

    
dx  = 1./32.
x   = linspace(-1,1,100)
y   = f(x)
plot(x,y)

dydx  = df(0)       #slope on x=x[0]
plot(x,dydx)            #plot slope

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


and the result is



Could we do something about it? Of course. We just needed small adjustment on the code.

Instead using value of the point and the next, x and x+dx, we use x-dx/2 and x+dx/2 to calculate the difference, so it will be fair, :)

Let we evaluate the slope of x^2 at x=0 using  central difference and forward difference.

The code below is for "the fair" difference, :)

from pylab import *

def f(x):
    return (x*x)

def df(xc):
    m   = (f(xc+dx/2.)-f(xc-dx/2.))/(dx)
    c   = f(xc) - m * xc
    
    return (m*x+c)

    
dx  = 1./32.
x   = linspace(-1,1,100)
y   = f(x)
plot(x,y)

dydx  = df(0)       #slope on x=x[0]
plot(x,dydx)            #plot slope

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


..


No comments:

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)