Thursday, March 05, 2009

Limits and Derivatives and Ruby

I read this article about Lisp: http://funcall.blogspot.com/2009/03/not-lisp-again.html
I wanted to try doing the same in Ruby.
I didn't like his setting DX as a constant close to 0 to shortcut not creating a function to figure the limit.




lim=lambda{|f,h|
y=h
1.upto(1.0/0) {|p| ##to infinity
x=h+(1.0/10)**p ##increase how close x is to h 1.0,0.1,0.001 etc..
fx=f[x] ##get f(x)
break if y==fx ##if we start getting the same val, stop
y=fx ##store the last val
}
y ##return where we stopped
}
ddx=lambda {|f|
lambda {|x|
lim[lambda{|dx| ##the limit of the derivative function
(f[x+dx]-f[x])/dx
},0] #as h approaches 0
}
}


Here are some results
(Infinite limits) http://www.cliffsnotes.com/WileyCDA/CliffsReviewTopic/Infinite-Limits.topicArticleId-39909,articleId-39873.html

irb(main):319:0> g=lambda{|x| 1/(x**2)}
=> #
irb(main):320:0> lim[g,0]
=> Infinity
irb(main):321:0> g=lambda{|x| (1/(x**2))-(1/(x**3))}
=> #
irb(main):322:0> lim[g,0]
=> -Infinity

Derivatives

irb(main):326:0> g=lambda{|x| x**3}
=> #
irb(main):327:0> ddx[g][2]
=> 12.0000009928844


I tried for hours to get the limit to resolve to a nice integer... but could never quite get it to be more precise. I did this because i googled "derivatives calculus ruby" and couldn't find anything about this. Why not?

No comments: