Created
March 17, 2017 08:12
-
-
Save thinkphp/c8265a1b4f5d5f75abd7f3871f83a86f to your computer and use it in GitHub Desktop.
natural logarithm in ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def f x,a | |
Math.exp(x)-a | |
end | |
def ln a | |
lo, hi = 0, a | |
anEPS = 0.0001 | |
while (lo-hi).abs >= anEPS | |
m = ((lo+hi)/2.0).to_f | |
if f(m,a) < 0 | |
lo = m | |
else | |
hi = m | |
end | |
end | |
((lo+hi)/2.0).to_f | |
end | |
class NatLog | |
def initialize( number ) | |
@a = number | |
end | |
def f(x,a) | |
Math.exp(x)-a | |
end | |
def compute | |
lo, hi = 0, @a | |
anEPS = 0.0001 | |
while (lo-hi).abs >= anEPS | |
m = ((lo+hi)/2.0).to_f | |
if self.f(m, @a) < 0 | |
lo = m | |
else | |
hi = m | |
end | |
end | |
((lo+hi)/2.0).to_f | |
end | |
end | |
p Math.log(9) | |
p ln(9) | |
ob = NatLog.new(9) | |
p ob.compute |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment