Skip to content

Instantly share code, notes, and snippets.

@thinkphp
Created March 17, 2017 08:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thinkphp/c8265a1b4f5d5f75abd7f3871f83a86f to your computer and use it in GitHub Desktop.
Save thinkphp/c8265a1b4f5d5f75abd7f3871f83a86f to your computer and use it in GitHub Desktop.
natural logarithm in ruby
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