From 3fe728e76b5020fbe0277ffc039e79f3c2834229 Mon Sep 17 00:00:00 2001 From: shigek Date: Fri, 15 Aug 2003 14:13:49 +0000 Subject: sqrt() & atan() added. git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@4394 b2dd03c8-39d4-4d8f-98ff-823fe69b080e --- ext/bigdecimal/lib/bigdecimal/math.rb | 44 +++++++++++++++++++++++++++++++---- 1 file changed, 39 insertions(+), 5 deletions(-) (limited to 'ext/bigdecimal') diff --git a/ext/bigdecimal/lib/bigdecimal/math.rb b/ext/bigdecimal/lib/bigdecimal/math.rb index 7921e7cc50..7f3c293268 100644 --- a/ext/bigdecimal/lib/bigdecimal/math.rb +++ b/ext/bigdecimal/lib/bigdecimal/math.rb @@ -1,16 +1,29 @@ # # Contents: -# sin(x, prec) -# cos(x, prec) -# exp(x, prec) -# log(x, prec) -# PI (prec) +# sqrt(x, prec) +# sin (x, prec) +# cos (x, prec) +# atan(x, prec) Note: |x|<1, x=0.9999 may not converge. +# exp (x, prec) +# log (x, prec) +# PI (prec) # # where: # x ... BigDecimal number to be computed. # prec ... Number of digits to be obtained. # +# Usage: +# require "bigdecimal" +# require "bigdecimal/math.rb" +# include BigMath +# a = BigDecimal((PI(1000)/2).to_s) +# puts sin(a,1000) # => 0.10000000000000000000......E1 +# module BigMath + def sqrt(x,prec) + x.sqrt(prec) + end + def sin(x, prec) raise ArgumentError, "Zero or negative precision for sin" if prec <= 0 return BigDecimal("NaN") if x.infinite? || x.nan? @@ -63,6 +76,27 @@ module BigMath y end + def atan(x, prec) + raise ArgumentError, "Zero or negative precision for sin" if prec <= 0 + return BigDecimal("NaN") if x.infinite? || x.nan? + raise ArgumentError, "x.abs must be less than 1.0" if x.abs>=1 + n = prec + BigDecimal.double_fig + n2 = n+n + y = x; + d = y; + t = x; + r = BigDecimal("3"); + x2 = x*x + while d.nonzero? && ((m = n - (y.exponent - d.exponent).abs) > 0) + m = BigDecimal.double_fig if m < BigDecimal.double_fig + t = -t.mult(x2,n2) + d = t.div(r,m) + y += d + r += 2 + end + y + end + def exp(x, prec) raise ArgumentError, "Zero or negative precision for sin" if prec <= 0 return BigDecimal("NaN") if x.infinite? || x.nan? -- cgit v1.2.3