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:
Post a Comment