Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Added bigdecimal extension.

  • Loading branch information...
commit 0eb8c0fa4d1f61187fec223f250b39bf3ca5d492 1 parent 97675a2
@brixen brixen authored
View
706 lib/bigdecimal.rb
@@ -1,705 +1 @@
-# depends on: class.rb numeric.rb regexp.rb string.rb
-
-def BigDecimal(string, _precs=0)
- BigDecimal.new(string, _precs)
-end
-
-class BigDecimal < Numeric
- # See stdlib/ext/bigdecimal for MatzRuby implementation.
-
- attr_reader :digits
- protected :digits
-
- #############
- # Constants #
- #############
-
- SIGN_POSITIVE_ZERO = 1
- SIGN_NEGATIVE_ZERO = -1
- SIGN_POSITIVE_FINITE = 2
- SIGN_NEGATIVE_FINITE = -2
- SIGN_POSITIVE_INFINITE = 3
- SIGN_NEGATIVE_INFINITE = -3
- SIGN_NaN = 0 # is this correct?
-
- PLUS = '+'
- MINUS = '-'
- RADIX = '.'
- EXP = 'E'
- SIGNS = {-1 => MINUS, 0 => nil, 1 => PLUS}
-
- # Global upper limit of the precision newly allocated
- @@prec_limit = 0
-
- VERSION = "1.0.1" # like Ruby 1.8.6
-
- #################
- # Class methods #
- #################
- def self.induced_from(obj)
- case obj
- when BigDecimal
- obj
- when Bignum, Fixnum
- BigDecimal(obj.to_s)
- else
- raise TypeError, "failed to convert #{obj.class} into BigDecimal"
- end
- end
-
- def self.limit(val=nil)
- old_limit = @@prec_limit
- @@prec_limit = val if !val.nil?
- return old_limit
- end
-
- def self.ver
- VERSION
- end
-
- ###############################
- # Constructor and basic tests #
- ###############################
-
- # call-seq:
- # BigDecimal("3.14159") => big_decimal
- # BigDecimal("3.14159", 10) => big_decimal
- def initialize(_val, _precs=0)
- # set up defaults
- @sign = PLUS
- @digits = 0 # decimal point is assumed at beginning; exp is assigned on this basis
- @exp = 0
- @special = nil # 'n' for NaN, 'i' for Infinity, nil otherwise
-
- v = _val.strip
- if v == "NaN"
- @special = 'n'
- @precs = 0
- elsif v =~ /^[-+]?Infinity$/
- @special = 'i'
- @sign = MINUS if v =~ /-/
- @precs = 0
- else
- v = _val.gsub('_', '')
- m = /^\s*(([-+]?)(\d*)(?:\.(\d*))?(?:[EeDd]([-+]?\d+))?).*$/.match(v)
- if !m.nil?
- @sign = m[2] unless m[2].to_s.empty?
- int = m[3].to_s.gsub(/^0*/, '')
- frac = m[4].to_s
- fraczeros = /^0*/.match(frac)[0]
- @exp = m[5].to_i + int.length
- if int.to_i == 0
- @exp -= (fraczeros.size == frac.size) ? 0 : fraczeros.length
- end
- @digits = (int + frac).gsub(/0*$/, '').to_i
- end
- @precs = [v.length, _precs].max
- end
- end
-
- # As for Float.finite? .
- # call-seq:
- # BigDecimal.new("Infinity").finite? => false
- # BigDecimal.new("NaN").finite? => true
- def finite?
- @special != 'i' && !self.nan?
- end
-
- def infinite?
- if self.finite? or self.nan?
- return nil
- else
- return (@sign + '1').to_i
- end
- end
-
- # As for Float.nan? .
- # call-seq:
- # BigDecimal.new("NaN").nan? => true
- # BigDecimal.new("123").nan? => false
- def nan?
- @special == 'n'
- end
-
- # True if positive or negative zero; false otherwise.
- # call-seq:
- # BigDecimal.new("0").zero? =>true
- # BigDecimal.new("-0").zero? =>true
- def zero?
- @digits.to_i == 0 and self.finite?
- end
-
- def precs
- if !self.finite?
- sigfigs = 0
- else
- sigfigs = @digits.to_s.length
- end
- [sigfigs, @precs]
- end
-
- ###############
- # Conversions #
- ###############
-
- def to_f
- if self.sign == SIGN_POSITIVE_INFINITE
- return +1.0/0.0
- elsif self.sign == SIGN_NEGATIVE_INFINITE
- return -1.0/0.0
- elsif self.nan?
- return 0.0/0.0
- end
-
- self.to_s("F").to_f
- end
-
- def to_i
- if !self.finite?
- return nil
- end
- self.fix.to_s("F").to_i
- end
-
- def to_s(arg='')
- # parse the argument for format specs
- positive = case arg
- when /\+/ then PLUS.clone
- when / / then ' '
- else ''
- end
- format = arg =~ /F/ ? :float : :eng
- spacing = arg.to_i
-
- nan = 'NaN'
- infinity = 'Infinity'
-
- if self.nan?
- return nan
- end
-
- if @sign == PLUS
- str = positive
- else
- str = MINUS.clone
- end
-
- if self.finite?
- value = @digits.to_s
- if format == :float
- # get the decimal point in place
- if @exp >= value.length
- value << ('0' * (@exp - value.length)) + RADIX + '0'
- elsif @exp > 0
- value = value[0, @exp] + RADIX + value[@exp..-1]
- elsif @exp <= 0
- value = '0' + RADIX + ('0' * -@exp) + value
- end
- elsif format == :eng
- value = '0' + RADIX + value
- if @exp != 0
- value << EXP + @exp.to_s
- end
- end
-
- if spacing != 0
- m = /^(\d*)(?:(#{RADIX})(\d*)(.*))?$/.match(value)
- left, myradix, right, extra = m[1, 4].collect{|s| s.to_s}
- right_frags = []
- 0.step(right.length, spacing) do |n|
- right_frags.push right[n, spacing]
- end
-
- left_frags = []
- tfel = left.reverse
- 0.step(left.length, spacing) do |n|
- left_frags.unshift tfel[n, spacing].reverse
- end
-
- right = right_frags.join(' ').strip
- left = left_frags.join(' ').strip
- value = left.to_s + myradix.to_s + right.to_s + extra.to_s
- end
- str << value
- else
- str << infinity
- end
- return str
- end
-
- def inspect
- str = '#<BigDecimal:'
- str << [nil, "'#{self.to_s}'", "#{precs[0]}(#{precs[1]})"].join(',')
- str << '>'
- return str
- end
-
- def coerce(other)
- if other.kind_of?(BigDecimal)
- [other, self]
- else
- [BigDecimal(other.to_s), self]
- end
- end
-
- #########################
- # Arithmetic operations #
- #########################
-
- # These are stubbed out until we implement them so that their respective specfiles don't crash.
-
- def add(other, precs)
- if !other.kind_of?(BigDecimal)
- return self.add(BigDecimal(other.to_s), precs)
- elsif self.nan? or other.nan?
- return BigDecimal("NaN")
- elsif !self.finite? and !other.finite? and self.sign != other.sign
- # infinity + -infinity
- return BigDecimal("NaN")
- elsif !self.finite? or other.zero?
- return self
- elsif !other.finite? or self.zero?
- return other
- elsif self.exponent == other.exponent
- sd, od = self.align(other)
- sum = (sd.to_i * (self.sign <=> 0)) + (od.to_i * (other.sign <=> 0))
- s = sum.abs.to_s
- sumdiff = s.length - sd.length
- if sum < 0
- s = MINUS + RADIX + s
- else
- s = RADIX + s
- end
- BigDecimal(s + EXP + (self.exponent + sumdiff).to_s, precs)
- elsif self.exponent == 0 or other.exponent == 0
- if self.exponent == 0
- z = self
- nz = other
- else
- z = other
- nz = self
- end
- # so z is the one with the 0 exponent
- zd = z.digits.to_s
- nzd = nz.digits.to_s
- nzx = nz.exponent
-
- if nzx > 0
- zd = ('0' * nzx) + zd
- else # if nzx < 0
- nzd = ('0' * nzx.abs) + nzd
- end
-
- zd, nzd = BigDecimal.align(zd, nzd)
-
- l = zd.length
- sum = (nzd.to_s.to_i * (nz.sign <=> 0)) + (zd.to_s.to_i * (z.sign <=> 0))
- sumsign = sum < 0 ? MINUS : PLUS
- s = sum.abs.to_s
- sumdiff = s.length - zd.length
- BigDecimal(sumsign + RADIX + s + EXP + (sumdiff + [nzx, 0].max).to_s, precs)
- else
- a, b, extra = reduce(self, other)
- sum = a + b
- BigDecimal(SIGNS[sum.sign <=> 0].to_s + RADIX + sum.digits.to_s + EXP + (sum.exponent + extra).to_s, precs)
- end
- end
-
- def +(other)
- self.add(other, 0)
- end
-
- def sub(other, precs)
- self.add(-other, precs)
- end
-
- def -(other)
- self + -other
- end
-
- def mult(other, precs)
- if !other.kind_of?(BigDecimal)
- return self.mult(BigDecimal(other.to_s), precs)
- elsif (self.infinite? and other.zero?) or (self.zero? and other.infinite?)
- return BigDecimal("NaN")
- elsif (self.nan? or other.nan?)
- return BigDecimal("NaN")
- elsif (self.zero? or other.zero?)
- return BigDecimal("0") if (self.sign * other.sign) > 0
- return BigDecimal("-0") if (self.sign * other.sign) < 0
- elsif !self.finite?
- if (self.sign * other.sign < 0) == self.sign < 0
- return self
- else
- return -self
- end
- elsif !other.finite?
- if (self.sign * other.sign < 0) == self.sign < 0
- return other
- else
- return -other
- end
- end
-
- sd = self.digits
- od = other.digits
-
- # figure out how many decimal places we're dealing with
- sp = sd.to_s.length - self.exponent
- op = od.to_s.length - other.exponent
-
- a = sd * (self < 0 ? -1 : 1)
- b = od * (other < 0 ? -1 : 1)
- prod = a * b
- pa = prod.abs
- BigDecimal([SIGNS[prod <=> 0], RADIX, pa, EXP, pa.to_s.length - (sp + op)].join)
- end
-
- def *(other)
- self.mult(other, 0)
- end
-
- def quo(other)
- self.div(other, 0)
- end
- alias / quo
-
- def divide(other)
- b, a = coerce other
- a / b
- end
-
- def div(other, precs = nil)
- if !other.kind_of?(BigDecimal)
- self.quo(BigDecimal(other.to_s))
- elsif self.nan? or other.nan?
- return BigDecimal("NaN")
- elsif other.infinite?
- if precs.nil? or self.infinite?
- return BigDecimal("NaN")
- else
- return BigDecimal("0")
- end
- elsif other.zero?
- return BigDecimal("NaN") if precs.nil? or self.zero?
- return BigDecimal("Infinity") * other.sign
- elsif (other.digits == 1) and self.infinite?
- if precs.nil?
- return BigDecimal("NaN")
- else
- return self * other.sign
- end
- elsif !self.exponent.zero? and !other.exponent.zero?
- a, b, extra = reduce(self, other)
- q = precs.nil? ? (a / b).floor : (a / b)
- p = precs.nil? ? q.to_s.length : precs
- p.zero? ? BigDecimal(q.to_s) : BigDecimal(q.to_s[0..p+1])
- else
- sa, oa = self.align(other)
- q = [SIGNS[self <=> 0], sa].join.to_f / [SIGNS[other <=> 0], oa].join.to_f
- BigDecimal([q, EXP, self.exponent - other.exponent].join)
- end
- end
-
- def remainder(other)
- mod = self % other
-
- if (self.sign * other.sign < 0)
- return mod - other
- else
- return mod
- end
- end
-
- def modulo(other)
- self.divmod(other)[1]
- end
- alias % modulo
-
- def divmod(other)
- arr = []
-
- raise TypeError if other.kind_of?(String)
- other = BigDecimal(other.to_s) if other.kind_of?(Integer)
-
- if self.infinite? or self.nan?
- return [BigDecimal("NaN"), BigDecimal("NaN")]
- end
-
- if other.infinite? or other.nan? or other.zero?
- return [BigDecimal("NaN"), BigDecimal("NaN")]
- end
-
- first = (self / other).floor
- second = self - (first * other)
-
- arr << first.to_i << second.to_f if other.kind_of?(Float)
- arr << first << second
- end
-
- def sqrt(other)
- end
-
- # Raises self to an integer power.
- def power(other)
- one = BigDecimal("1")
- if !self.finite?
- return BigDecimal("NaN")
- elsif other.zero? or self == 1
- return one
- elsif self.zero?
- if other > 0
- return BigDecimal("0")
- else
- return BigDecimal("Infinity")
- end
- elsif other < 0
- return one / (self ** other.abs)
- elsif !self.exponent.zero?
- base = BigDecimal([@sign, RADIX, @digits].join)
- exp = self.exponent
- n = base ** other
- return BigDecimal([SIGNS[n <=> 0], RADIX, n.digits, EXP, (exp * other) + n.exponent].join)
- elsif other == 1
- return self
- elsif other % 2 == 1
- return self * (self ** (other - 1))
- else
- return (self * self) ** (other / 2)
- end
- end
- alias ** power
-
- # Unary minus
- def -@
- if self.nan?
- return self
- end
- s = self.to_s
- if @sign == MINUS
- BigDecimal(s[1..-1])
- else
- BigDecimal(MINUS + s)
- end
- end
-
- def <=>(other)
- if other.nil?
- return nil
- elsif !other.kind_of?(BigDecimal)
- return self <=> self.coerce(other)[0]
- elsif self.nan? or other.nan?
- return nil
- elsif self.eql?(other)
- return 0
- else
- result = (self.sign <=> other.sign).nonzero? || \
- (self.exponent <=> other.exponent).nonzero? || \
- (self.to_i <=> other.to_i).nonzero? || \
- ((self - other).sign <=> BigDecimal("0").sign)
- return result
- end
- end
-
- # Apparently, 'include Comparable' doesn't work, so:
- def >(other)
- compare_method(other, 1)
- end
-
- def >=(other)
- return (self > other or self == other)
- end
-
- def <(other)
- compare_method(other, -1)
- end
-
- def <=(other)
- return (self < other or self == other)
- end
-
- def ==(other)
- compare_method(other, 0)
- end
-
- def eql?(other)
- if self.nan?
- return false
- elsif other.respond_to?(:nan?) and other.nan?
- return false
- elsif self.zero? and other.respond_to?(:zero?)
- return other.zero?
- elsif self.to_s == other.to_s
- return true
- elsif !other.kind_of?(BigDecimal)
- return self.eql?(BigDecimal(other.to_s))
- else
- return false
- end
- end
- alias === eql?
-
- ####################
- # Other operations #
- ####################
-
- # I'm trying to keep these in alphabetical order unless a good reason develops to do otherwise.
-
- def abs
- if self.nan? or @sign == PLUS
- return self
- else
- s = self.to_s.sub(/^-/, '') # strip minus sign
- BigDecimal(s)
- end
- end
-
- def ceil(n = 0)
- if self.infinite?
- return self
- elsif !n.zero?
- x = (BigDecimal([@sign, '0', RADIX, @digits, EXP, self.exponent + n].join)).ceil
- return BigDecimal([@sign, '0', RADIX, x.digits, EXP, x.exponent - n].join)
- elsif self.frac.zero?
- return self
- elsif self < 0
- return self.fix
- else
- return self.fix + BigDecimal("1")
- end
- end
-
- # Returns the exponent as a Fixnum (or 0 if out of range), such that the absolute value of the base is between 0 and 1. This is not the power function.
- # call-seq:
- # BigDecimal("0.125e3").exponent => 3
- # BigDecimal("3000").exponent => 4
- #
- def exponent
- return @exp
- end
-
- def fix
- d = @digits.to_s.length
- if !self.finite? or d <= @exp
- return self
- elsif @exp < 0
- return BigDecimal("#{@sign}0")
- end
- s = self.to_s("F").split(RADIX)[0] # this includes the sign
- BigDecimal(s)
- end
-
- def floor(n = 0)
- -((-self).ceil(n))
- end
-
- def frac
- if !self.finite?
- return self
- elsif @digits.to_s.length <= @exp
- return BigDecimal("0")
- end
- s = self.to_s("F").split(RADIX)[1] # the part after the decimal point
- BigDecimal(@sign + RADIX + s)
- end
-
- def sign
- if self.nan?
- SIGN_NaN
- elsif self.zero?
- @sign == PLUS ? SIGN_POSITIVE_ZERO : SIGN_NEGATIVE_ZERO
- elsif self.finite?
- @sign == PLUS ? SIGN_POSITIVE_FINITE : SIGN_NEGATIVE_FINITE
- else # infinite
- @sign == PLUS ? SIGN_POSITIVE_INFINITE : SIGN_NEGATIVE_INFINITE
- end
- end
-
- def split
- arr = []
- base = 10
-
- if self.sign > 0
- sgn = 1
- elsif self.sign < 0
- sgn = -1
- else
- sgn = 0
- end
-
- if self.infinite?
- value = "Infinity"
- elsif self.nan?
- value = "NaN"
- else
- value = @digits.to_s
- end
-
- arr << sgn << value << base << @exp
- end
-
- def truncate(prec = nil)
- if !self.finite?
- return self
- elsif prec.nil?
- self.fix
- else
- e = [0, @exp + prec].max
- s = @digits.to_s[0, e]
- BigDecimal(@sign + '0' + RADIX + s + EXP + @exp.to_s)
- end
- end
-
- ############################
- # Internal utility methods #
- ############################
-
- protected
-
- # Takes two BigDecimals and returns an array of their digit strings,
- # with the shorter one right-padded with zeros so they're the same length.
- # Can also take a digit string itself.
- # call-seq:
- # BigDecimal("12").align(BigDecimal("0.0056789")) => ["12000", "56789"]
- # BigDecimal("8.765").align("43") => ["8765", "4300"]
- def align(y) #:nodoc:
- xd = self.digits.to_s
- yd = y.kind_of?(BigDecimal) ? y.digits.to_s : y
- BigDecimal.align(xd, yd)
- end
-
- # Like BigDecimal#align, but can take two digit strings.
- # call-seq:
- # BigDecimal.align("8765", "43") => ["8765", "4300"]
- def self.align(x, y) #:nodoc:
- xd = x.clone
- yd = y.clone
- diff = xd.length - yd.length
- if diff > 0
- yd << '0' * diff
- else
- xd << '0' * diff.abs
- end
- [xd, yd]
- end
-
- # Wrapper for implementing comparison methods.
- def compare_method(other, val)
- # if !self.nan? and other.respond_to?(:nan?) and other.nan?
- # raise ArgumentError, "Can't compare #{self} to NaN", caller
- # else
- result = (self <=> other)
- return result.nil? ? nil : result == val
- # end
- end
-
- # Reduces exponents and returns [a, b, extra].
- # call-seq:
- # reduce(BigDecimal("8E5"), BigDecimal("6E2")) => [BigDecimal("8E3"), BigDecimal("6"), 2]
- def reduce(x, y)
- extra = [x.exponent, y.exponent].min
- a = BigDecimal(SIGNS[x.sign <=> 0].to_s + RADIX + x.digits.to_s + EXP + (x.exponent - extra).to_s)
- b = BigDecimal(SIGNS[y.sign <=> 0].to_s + RADIX + y.digits.to_s + EXP + (y.exponent - extra).to_s)
- [a, b, extra]
- end
-end
+require 'ext/bigdecimal/bigdecimal'
View
85 lib/bigdecimal/jacobian.rb
@@ -0,0 +1,85 @@
+#
+# require 'bigdecimal/jacobian'
+#
+# Provides methods to compute the Jacobian matrix of a set of equations at a
+# point x. In the methods below:
+#
+# f is an Object which is used to compute the Jacobian matrix of the equations.
+# It must provide the following methods:
+#
+# f.values(x):: returns the values of all functions at x
+#
+# f.zero:: returns 0.0
+# f.one:: returns 1.0
+# f.two:: returns 1.0
+# f.ten:: returns 10.0
+#
+# f.eps:: returns the convergence criterion (epsilon value) used to determine whether two values are considered equal. If |a-b| < epsilon, the two values are considered equal.
+#
+# x is the point at which to compute the Jacobian.
+#
+# fx is f.values(x).
+#
+module Jacobian
+ #--
+ def isEqual(a,b,zero=0.0,e=1.0e-8)
+ aa = a.abs
+ bb = b.abs
+ if aa == zero && bb == zero then
+ true
+ else
+ if ((a-b)/(aa+bb)).abs < e then
+ true
+ else
+ false
+ end
+ end
+ end
+ #++
+
+ # Computes the derivative of f[i] at x[i].
+ # fx is the value of f at x.
+ def dfdxi(f,fx,x,i)
+ nRetry = 0
+ n = x.size
+ xSave = x[i]
+ ok = 0
+ ratio = f.ten*f.ten*f.ten
+ dx = x[i].abs/ratio
+ dx = fx[i].abs/ratio if isEqual(dx,f.zero,f.zero,f.eps)
+ dx = f.one/f.ten if isEqual(dx,f.zero,f.zero,f.eps)
+ until ok>0 do
+ s = f.zero
+ deriv = []
+ if(nRetry>100) then
+ raize "Singular Jacobian matrix. No change at x[" + i.to_s + "]"
+ end
+ dx = dx*f.two
+ x[i] += dx
+ fxNew = f.values(x)
+ for j in 0...n do
+ if !isEqual(fxNew[j],fx[j],f.zero,f.eps) then
+ ok += 1
+ deriv <<= (fxNew[j]-fx[j])/dx
+ else
+ deriv <<= f.zero
+ end
+ end
+ x[i] = xSave
+ end
+ deriv
+ end
+
+ # Computes the Jacobian of f at x. fx is the value of f at x.
+ def jacobian(f,fx,x)
+ n = x.size
+ dfdx = Array::new(n*n)
+ for i in 0...n do
+ df = dfdxi(f,fx,x,i)
+ for j in 0...n do
+ dfdx[j*n+i] = df[j]
+ end
+ end
+ dfdx
+ end
+end
View
84 lib/bigdecimal/ludcmp.rb
@@ -0,0 +1,84 @@
+#
+# Solves a*x = b for x, using LU decomposition.
+#
+module LUSolve
+ # Performs LU decomposition of the n by n matrix a.
+ def ludecomp(a,n,zero=0,one=1)
+ prec = BigDecimal.limit(nil)
+ ps = []
+ scales = []
+ for i in 0...n do # pick up largest(abs. val.) element in each row.
+ ps <<= i
+ nrmrow = zero
+ ixn = i*n
+ for j in 0...n do
+ biggst = a[ixn+j].abs
+ nrmrow = biggst if biggst>nrmrow
+ end
+ if nrmrow>zero then
+ scales <<= one.div(nrmrow,prec)
+ else
+ raise "Singular matrix"
+ end
+ end
+ n1 = n - 1
+ for k in 0...n1 do # Gaussian elimination with partial pivoting.
+ biggst = zero;
+ for i in k...n do
+ size = a[ps[i]*n+k].abs*scales[ps[i]]
+ if size>biggst then
+ biggst = size
+ pividx = i
+ end
+ end
+ raise "Singular matrix" if biggst<=zero
+ if pividx!=k then
+ j = ps[k]
+ ps[k] = ps[pividx]
+ ps[pividx] = j
+ end
+ pivot = a[ps[k]*n+k]
+ for i in (k+1)...n do
+ psin = ps[i]*n
+ a[psin+k] = mult = a[psin+k].div(pivot,prec)
+ if mult!=zero then
+ pskn = ps[k]*n
+ for j in (k+1)...n do
+ a[psin+j] -= mult.mult(a[pskn+j],prec)
+ end
+ end
+ end
+ end
+ raise "Singular matrix" if a[ps[n1]*n+n1] == zero
+ ps
+ end
+
+ # Solves a*x = b for x, using LU decomposition.
+ #
+ # a is a matrix, b is a constant vector, x is the solution vector.
+ #
+ # ps is the pivot, a vector which indicates the permutation of rows performed
+ # during LU decomposition.
+ def lusolve(a,b,ps,zero=0.0)
+ prec = BigDecimal.limit(nil)
+ n = ps.size
+ x = []
+ for i in 0...n do
+ dot = zero
+ psin = ps[i]*n
+ for j in 0...i do
+ dot = a[psin+j].mult(x[j],prec) + dot
+ end
+ x <<= b[ps[i]] - dot
+ end
+ (n-1).downto(0) do |i|
+ dot = zero
+ psin = ps[i]*n
+ for j in (i+1)...n do
+ dot = a[psin+j].mult(x[j],prec) + dot
+ end
+ x[i] = (x[i]-dot).div(a[psin+i],prec)
+ end
+ x
+ end
+end
View
235 lib/bigdecimal/math.rb
@@ -0,0 +1,235 @@
+#
+#--
+# Contents:
+# 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)
+# E (prec) == exp(1.0,prec)
+#
+# where:
+# x ... BigDecimal number to be computed.
+# |x| must be small enough to get convergence.
+# prec ... Number of digits to be obtained.
+#++
+#
+# Provides mathematical functions.
+#
+# Example:
+#
+# require "bigdecimal"
+# require "bigdecimal/math"
+#
+# include BigMath
+#
+# a = BigDecimal((PI(100)/2).to_s)
+# puts sin(a,100) # -> 0.10000000000000000000......E1
+#
+module BigMath
+
+ # Computes the square root of x to the specified number of digits of
+ # precision.
+ #
+ # BigDecimal.new('2').sqrt(16).to_s
+ # -> "0.14142135623730950488016887242096975E1"
+ #
+ def sqrt(x,prec)
+ x.sqrt(prec)
+ end
+
+ # Computes the sine of x to the specified number of digits of precision.
+ #
+ # If x is infinite or NaN, returns NaN.
+ def sin(x, prec)
+ raise ArgumentError, "Zero or negative precision for sin" if prec <= 0
+ return BigDecimal("NaN") if x.infinite? || x.nan?
+ n = prec + BigDecimal.double_fig
+ one = BigDecimal("1")
+ two = BigDecimal("2")
+ x1 = x
+ x2 = x.mult(x,n)
+ sign = 1
+ y = x
+ d = y
+ i = one
+ z = one
+ while d.nonzero? && ((m = n - (y.exponent - d.exponent).abs) > 0)
+ m = BigDecimal.double_fig if m < BigDecimal.double_fig
+ sign = -sign
+ x1 = x2.mult(x1,n)
+ i += two
+ z *= (i-one) * i
+ d = sign * x1.div(z,m)
+ y += d
+ end
+ y
+ end
+
+ # Computes the cosine of x to the specified number of digits of precision.
+ #
+ # If x is infinite or NaN, returns NaN.
+ def cos(x, prec)
+ raise ArgumentError, "Zero or negative precision for cos" if prec <= 0
+ return BigDecimal("NaN") if x.infinite? || x.nan?
+ n = prec + BigDecimal.double_fig
+ one = BigDecimal("1")
+ two = BigDecimal("2")
+ x1 = one
+ x2 = x.mult(x,n)
+ sign = 1
+ y = one
+ d = y
+ i = BigDecimal("0")
+ z = one
+ while d.nonzero? && ((m = n - (y.exponent - d.exponent).abs) > 0)
+ m = BigDecimal.double_fig if m < BigDecimal.double_fig
+ sign = -sign
+ x1 = x2.mult(x1,n)
+ i += two
+ z *= (i-one) * i
+ d = sign * x1.div(z,m)
+ y += d
+ end
+ y
+ end
+
+ # Computes the arctangent of x to the specified number of digits of precision.
+ #
+ # If x is infinite or NaN, returns NaN.
+ # Raises an argument error if x > 1.
+ def atan(x, prec)
+ raise ArgumentError, "Zero or negative precision for atan" 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
+ y = x
+ d = y
+ t = x
+ r = BigDecimal("3")
+ x2 = x.mult(x,n)
+ while d.nonzero? && ((m = n - (y.exponent - d.exponent).abs) > 0)
+ m = BigDecimal.double_fig if m < BigDecimal.double_fig
+ t = -t.mult(x2,n)
+ d = t.div(r,m)
+ y += d
+ r += 2
+ end
+ y
+ end
+
+ # Computes the value of e (the base of natural logarithms) raised to the
+ # power of x, to the specified number of digits of precision.
+ #
+ # If x is infinite or NaN, returns NaN.
+ #
+ # BigMath::exp(BigDecimal.new('1'), 10).to_s
+ # -> "0.271828182845904523536028752390026306410273E1"
+ def exp(x, prec)
+ raise ArgumentError, "Zero or negative precision for exp" if prec <= 0
+ return BigDecimal("NaN") if x.infinite? || x.nan?
+ n = prec + BigDecimal.double_fig
+ one = BigDecimal("1")
+ x1 = one
+ y = one
+ d = y
+ z = one
+ i = 0
+ while d.nonzero? && ((m = n - (y.exponent - d.exponent).abs) > 0)
+ m = BigDecimal.double_fig if m < BigDecimal.double_fig
+ x1 = x1.mult(x,n)
+ i += 1
+ z *= i
+ d = x1.div(z,m)
+ y += d
+ end
+ y
+ end
+
+ # Computes the natural logarithm of x to the specified number of digits
+ # of precision.
+ #
+ # Returns x if x is infinite or NaN.
+ #
+ def log(x, prec)
+ raise ArgumentError, "Zero or negative argument for log" if x <= 0 || prec <= 0
+ return x if x.infinite? || x.nan?
+ one = BigDecimal("1")
+ two = BigDecimal("2")
+ n = prec + BigDecimal.double_fig
+ x = (x - one).div(x + one,n)
+ x2 = x.mult(x,n)
+ y = x
+ d = y
+ i = one
+ while d.nonzero? && ((m = n - (y.exponent - d.exponent).abs) > 0)
+ m = BigDecimal.double_fig if m < BigDecimal.double_fig
+ x = x2.mult(x,n)
+ i += two
+ d = x.div(i,m)
+ y += d
+ end
+ y*two
+ end
+
+ # Computes the value of pi to the specified number of digits of precision.
+ def PI(prec)
+ raise ArgumentError, "Zero or negative argument for PI" if prec <= 0
+ n = prec + BigDecimal.double_fig
+ zero = BigDecimal("0")
+ one = BigDecimal("1")
+ two = BigDecimal("2")
+
+ m25 = BigDecimal("-0.04")
+ m57121 = BigDecimal("-57121")
+
+ pi = zero
+
+ d = one
+ k = one
+ w = one
+ t = BigDecimal("-80")
+ while d.nonzero? && ((m = n - (pi.exponent - d.exponent).abs) > 0)
+ m = BigDecimal.double_fig if m < BigDecimal.double_fig
+ t = t*m25
+ d = t.div(k,m)
+ k = k+two
+ pi = pi + d
+ end
+
+ d = one
+ k = one
+ w = one
+ t = BigDecimal("956")
+ while d.nonzero? && ((m = n - (pi.exponent - d.exponent).abs) > 0)
+ m = BigDecimal.double_fig if m < BigDecimal.double_fig
+ t = t.div(m57121,n)
+ d = t.div(k,m)
+ pi = pi + d
+ k = k+two
+ end
+ pi
+ end
+
+ # Computes e (the base of natural logarithms) to the specified number of
+ # digits of precision.
+ def E(prec)
+ raise ArgumentError, "Zero or negative precision for E" if prec <= 0
+ n = prec + BigDecimal.double_fig
+ one = BigDecimal("1")
+ y = one
+ d = y
+ z = one
+ i = 0
+ while d.nonzero? && ((m = n - (y.exponent - d.exponent).abs) > 0)
+ m = BigDecimal.double_fig if m < BigDecimal.double_fig
+ i += 1
+ z *= i
+ d = one.div(z,m)
+ y += d
+ end
+ y
+ end
+end
View
77 lib/bigdecimal/newton.rb
@@ -0,0 +1,77 @@
+#
+# newton.rb
+#
+# Solves the nonlinear algebraic equation system f = 0 by Newton's method.
+# This program is not dependent on BigDecimal.
+#
+# To call:
+# n = nlsolve(f,x)
+# where n is the number of iterations required,
+# x is the initial value vector
+# f is an Object which is used to compute the values of the equations to be solved.
+# It must provide the following methods:
+#
+# f.values(x):: returns the values of all functions at x
+#
+# f.zero:: returns 0.0
+# f.one:: returns 1.0
+# f.two:: returns 1.0
+# f.ten:: returns 10.0
+#
+# f.eps:: returns the convergence criterion (epsilon value) used to determine whether two values are considered equal. If |a-b| < epsilon, the two values are considered equal.
+#
+# On exit, x is the solution vector.
+#
+require "bigdecimal/ludcmp"
+require "bigdecimal/jacobian"
+
+module Newton
+ include LUSolve
+ include Jacobian
+
+ def norm(fv,zero=0.0)
+ s = zero
+ n = fv.size
+ for i in 0...n do
+ s += fv[i]*fv[i]
+ end
+ s
+ end
+
+ def nlsolve(f,x)
+ nRetry = 0
+ n = x.size
+
+ f0 = f.values(x)
+ zero = f.zero
+ one = f.one
+ two = f.two
+ p5 = one/two
+ d = norm(f0,zero)
+ minfact = f.ten*f.ten*f.ten
+ minfact = one/minfact
+ e = f.eps
+ while d >= e do
+ nRetry += 1
+ # Not yet converged. => Compute Jacobian matrix
+ dfdx = jacobian(f,f0,x)
+ # Solve dfdx*dx = -f0 to estimate dx
+ dx = lusolve(dfdx,f0,ludecomp(dfdx,n,zero,one),zero)
+ fact = two
+ xs = x.dup
+ begin
+ fact *= p5
+ if fact < minfact then
+ raise "Failed to reduce function values."
+ end
+ for i in 0...n do
+ x[i] = xs[i] - dx[i]*fact
+ end
+ f0 = f.values(x)
+ dn = norm(f0,zero)
+ end while(dn>=d)
+ d = dn
+ end
+ nRetry
+ end
+end
View
60 lib/ext/bigdecimal/README
@@ -0,0 +1,60 @@
+
+ Ruby BIGDECIMAL(Variable Precision) extension library.
+ Copyright (C) 1999 by Shigeo Kobayashi(shigeo@tinyforest.gr.jp)
+
+BigDecimal is copyrighted free software by Shigeo Kobayashi <shigeo@tinyforest.gr.jp>.
+You can redistribute it and/or modify it under either the terms of the GPL
+(see COPYING file), or the conditions below:
+
+ 1. You may make and give away verbatim copies of the source form of the
+ software without restriction, provided that you duplicate all of the
+ original copyright notices and associated disclaimers.
+
+ 2. You may modify your copy of the software in any way, provided that
+ you do at least ONE of the following:
+
+ a) place your modifications in the Public Domain or otherwise
+ make them Freely Available, such as by posting said
+ modifications to Usenet or an equivalent medium, or by allowing
+ the author to include your modifications in the software.
+
+ b) use the modified software only within your corporation or
+ organization.
+
+ c) rename any non-standard executables so the names do not conflict
+ with standard executables, which must also be provided.
+
+ d) make other distribution arrangements with the author.
+
+ 3. You may distribute the software in object code or executable
+ form, provided that you do at least ONE of the following:
+
+ a) distribute the executables and library files of the software,
+ together with instructions (in the manual page or equivalent)
+ on where to get the original distribution.
+
+ b) accompany the distribution with the machine-readable source of
+ the software.
+
+ c) give non-standard executables non-standard names, with
+ instructions on where to get the original software distribution.
+
+ d) make other distribution arrangements with the author.
+
+ 4. You may modify and include the part of the software into any other
+ software (possibly commercial).
+
+ 5. THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR
+ IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
+ WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR
+ PURPOSE.
+
+* The Author
+
+Feel free to send comments and bug reports to the author. Here is the
+author's latest mail address:
+
+ shigeo@tinyforest.gr.jp
+
+-------------------------------------------------------
+created at: Thu Dec 22 1999
View
4,722 lib/ext/bigdecimal/bigdecimal.c
4,722 additions, 0 deletions not shown
View
220 lib/ext/bigdecimal/bigdecimal.h
@@ -0,0 +1,220 @@
+/*
+ *
+ * Ruby BigDecimal(Variable decimal precision) extension library.
+ *
+ * Copyright(C) 2002 by Shigeo Kobayashi(shigeo@tinyforest.gr.jp)
+ *
+ * You may distribute under the terms of either the GNU General Public
+ * License or the Artistic License, as specified in the README file
+ * of this BigDecimal distribution.
+ *
+ * NOTES:
+ * 2003-03-28 V1.0 checked in.
+ *
+ */
+
+#ifndef ____BIG_DECIMAL__H____
+#define ____BIG_DECIMAL__H____
+
+#if defined(__cplusplus)
+extern "C" {
+#endif
+
+/*
+ * NaN & Infinity
+ */
+#define SZ_NaN "NaN"
+#define SZ_INF "Infinity"
+#define SZ_PINF "+Infinity"
+#define SZ_NINF "-Infinity"
+
+/*
+ * #define VP_EXPORT other than static to let VP_ routines
+ * be called from outside of this module.
+ */
+#define VP_EXPORT static
+
+#define U_LONG unsigned long
+#define S_LONG long
+#define U_INT unsigned int
+#define S_INT int
+
+/* Exception codes */
+#define VP_EXCEPTION_ALL ((unsigned short)0x00FF)
+#define VP_EXCEPTION_INFINITY ((unsigned short)0x0001)
+#define VP_EXCEPTION_NaN ((unsigned short)0x0002)
+#define VP_EXCEPTION_UNDERFLOW ((unsigned short)0x0004)
+#define VP_EXCEPTION_OVERFLOW ((unsigned short)0x0001) /* 0x0008) */
+#define VP_EXCEPTION_ZERODIVIDE ((unsigned short)0x0001) /* 0x0010) */
+
+/* Following 2 exceptions cann't controlled by user */
+#define VP_EXCEPTION_OP ((unsigned short)0x0020)
+#define VP_EXCEPTION_MEMORY ((unsigned short)0x0040)
+
+/* Computation mode */
+#define VP_ROUND_MODE ((unsigned short)0x0100)
+#define VP_ROUND_UP 1
+#define VP_ROUND_DOWN 2
+#define VP_ROUND_HALF_UP 3
+#define VP_ROUND_HALF_DOWN 4
+#define VP_ROUND_CEIL 5
+#define VP_ROUND_FLOOR 6
+#define VP_ROUND_HALF_EVEN 7
+
+#define VP_SIGN_NaN 0 /* NaN */
+#define VP_SIGN_POSITIVE_ZERO 1 /* Positive zero */
+#define VP_SIGN_NEGATIVE_ZERO -1 /* Negative zero */
+#define VP_SIGN_POSITIVE_FINITE 2 /* Positive finite number */
+#define VP_SIGN_NEGATIVE_FINITE -2 /* Negative finite number */
+#define VP_SIGN_POSITIVE_INFINITE 3 /* Positive infinite number */
+#define VP_SIGN_NEGATIVE_INFINITE -3 /* Negative infinite number */
+
+/*
+ * VP representation
+ * r = 0.xxxxxxxxx *BASE**exponent
+ */
+typedef struct {
+ VALUE obj; /* Back pointer(VALUE) for Ruby object. */
+ U_LONG MaxPrec; /* Maximum precision size */
+ /* This is the actual size of pfrac[] */
+ /*(frac[0] to frac[MaxPrec] are available). */
+ U_LONG Prec; /* Current precision size. */
+ /* This indicates how much the. */
+ /* the array frac[] is actually used. */
+ S_INT exponent;/* Exponent part. */
+ short sign; /* Attributes of the value. */
+ /*
+ * ==0 : NaN
+ * 1 : Positive zero
+ * -1 : Negative zero
+ * 2 : Positive number
+ * -2 : Negative number
+ * 3 : Positive infinite number
+ * -3 : Negative infinite number
+ */
+ short flag; /* Not used in vp_routines,space for user. */
+ U_LONG frac[1]; /* Pointer to array of fraction part. */
+} Real;
+
+/*
+ * ------------------
+ * EXPORTables.
+ * ------------------
+ */
+
+VP_EXPORT Real *
+VpNewRbClass(U_LONG mx,char *str,VALUE klass);
+
+VP_EXPORT Real *VpCreateRbObject(U_LONG mx,const char *str);
+
+VP_EXPORT U_LONG VpBaseFig(void);
+VP_EXPORT U_LONG VpDblFig(void);
+VP_EXPORT U_LONG VpBaseVal(void);
+
+/* Zero,Inf,NaN (isinf(),isnan() used to check) */
+VP_EXPORT double VpGetDoubleNaN(void);
+VP_EXPORT double VpGetDoublePosInf(void);
+VP_EXPORT double VpGetDoubleNegInf(void);
+VP_EXPORT double VpGetDoubleNegZero(void);
+
+/* These 2 functions added at v1.1.7 */
+VP_EXPORT U_LONG VpGetPrecLimit(void);
+VP_EXPORT U_LONG VpSetPrecLimit(U_LONG n);
+
+/* Round mode */
+VP_EXPORT int VpIsRoundMode(unsigned long n);
+VP_EXPORT unsigned long VpGetRoundMode(void);
+VP_EXPORT unsigned long VpSetRoundMode(unsigned long n);
+
+VP_EXPORT int VpException(unsigned short f,const char *str,int always);
+#if 0
+VP_EXPORT int VpIsNegDoubleZero(double v);
+#endif
+VP_EXPORT U_LONG VpNumOfChars(Real *vp,const char *pszFmt);
+VP_EXPORT U_LONG VpInit(U_LONG BaseVal);
+VP_EXPORT void *VpMemAlloc(U_LONG mb);
+VP_EXPORT void VpFree(Real *pv);
+VP_EXPORT Real *VpAlloc(U_LONG mx, const char *szVal);
+VP_EXPORT int VpAsgn(Real *c,Real *a,int isw);
+VP_EXPORT int VpAddSub(Real *c,Real *a,Real *b,int operation);
+VP_EXPORT int VpMult(Real *c,Real *a,Real *b);
+VP_EXPORT int VpDivd(Real *c,Real *r,Real *a,Real *b);
+VP_EXPORT int VpComp(Real *a,Real *b);
+VP_EXPORT S_LONG VpExponent10(Real *a);
+VP_EXPORT void VpSzMantissa(Real *a,char *psz);
+VP_EXPORT int VpToSpecialString(Real *a,char *psz,int fPlus);
+VP_EXPORT void VpToString(Real *a,char *psz,int fFmt,int fPlus);
+VP_EXPORT void VpToFString(Real *a,char *psz,int fFmt,int fPlus);
+VP_EXPORT int VpCtoV(Real *a,const char *int_chr,U_LONG ni,const char *frac,U_LONG nf,const char *exp_chr,U_LONG ne);
+VP_EXPORT int VpVtoD(double *d,S_LONG *e,Real *m);
+VP_EXPORT void VpDtoV(Real *m,double d);
+#if 0
+VP_EXPORT void VpItoV(Real *m,S_INT ival);
+#endif
+VP_EXPORT int VpSqrt(Real *y,Real *x);
+VP_EXPORT int VpActiveRound(Real *y,Real *x,int f,int il);
+VP_EXPORT int VpMidRound(Real *y, int f, int nf);
+VP_EXPORT int VpLeftRound(Real *y, int f, int nf);
+VP_EXPORT void VpFrac(Real *y,Real *x);
+VP_EXPORT int VpPower(Real *y,Real *x,S_INT n);
+
+/* VP constants */
+VP_EXPORT Real *VpOne(void);
+
+/*
+ * ------------------
+ * MACRO definitions.
+ * ------------------
+ */
+#define Abs(a) (((a)>= 0)?(a):(-(a)))
+#define Max(a, b) (((a)>(b))?(a):(b))
+#define Min(a, b) (((a)>(b))?(b):(a))
+
+#define VpMaxPrec(a) ((a)->MaxPrec)
+#define VpPrec(a) ((a)->Prec)
+#define VpGetFlag(a) ((a)->flag)
+
+/* Sign */
+
+/* VpGetSign(a) returns 1,-1 if a>0,a<0 respectively */
+#define VpGetSign(a) (((a)->sign>0)?1:(-1))
+/* Change sign of a to a>0,a<0 if s = 1,-1 respectively */
+#define VpChangeSign(a,s) {if((s)>0) (a)->sign=(short)Abs((S_LONG)(a)->sign);else (a)->sign=-(short)Abs((S_LONG)(a)->sign);}
+/* Sets sign of a to a>0,a<0 if s = 1,-1 respectively */
+#define VpSetSign(a,s) {if((s)>0) (a)->sign=(short)VP_SIGN_POSITIVE_FINITE;else (a)->sign=(short)VP_SIGN_NEGATIVE_FINITE;}
+
+/* 1 */
+#define VpSetOne(a) {(a)->frac[0]=(a)->exponent=(a)->Prec=1;(a)->sign=VP_SIGN_POSITIVE_FINITE;}
+
+/* ZEROs */
+#define VpIsPosZero(a) ((a)->sign==VP_SIGN_POSITIVE_ZERO)
+#define VpIsNegZero(a) ((a)->sign==VP_SIGN_NEGATIVE_ZERO)
+#define VpIsZero(a) (VpIsPosZero(a) || VpIsNegZero(a))
+#define VpSetPosZero(a) ((a)->frac[0]=0,(a)->Prec=1,(a)->sign=VP_SIGN_POSITIVE_ZERO)
+#define VpSetNegZero(a) ((a)->frac[0]=0,(a)->Prec=1,(a)->sign=VP_SIGN_NEGATIVE_ZERO)
+#define VpSetZero(a,s) ( ((s)>0)?VpSetPosZero(a):VpSetNegZero(a) )
+
+/* NaN */
+#define VpIsNaN(a) ((a)->sign==VP_SIGN_NaN)
+#define VpSetNaN(a) ((a)->frac[0]=0,(a)->Prec=1,(a)->sign=VP_SIGN_NaN)
+
+/* Infinity */
+#define VpIsPosInf(a) ((a)->sign==VP_SIGN_POSITIVE_INFINITE)
+#define VpIsNegInf(a) ((a)->sign==VP_SIGN_NEGATIVE_INFINITE)
+#define VpIsInf(a) (VpIsPosInf(a) || VpIsNegInf(a))
+#define VpIsDef(a) ( !(VpIsNaN(a)||VpIsInf(a)) )
+#define VpSetPosInf(a) ((a)->frac[0]=0,(a)->Prec=1,(a)->sign=VP_SIGN_POSITIVE_INFINITE)
+#define VpSetNegInf(a) ((a)->frac[0]=0,(a)->Prec=1,(a)->sign=VP_SIGN_NEGATIVE_INFINITE)
+#define VpSetInf(a,s) ( ((s)>0)?VpSetPosInf(a):VpSetNegInf(a) )
+#define VpHasVal(a) (a->frac[0])
+#define VpIsOne(a) ((a->Prec==1)&&(a->frac[0]==1)&&(a->exponent==1))
+#define VpExponent(a) (a->exponent)
+#ifdef _DEBUG
+int VpVarCheck(Real * v);
+VP_EXPORT int VPrint(FILE *fp,char *cntl_chr,Real *a);
+#endif /* _DEBUG */
+
+#if defined(__cplusplus)
+} /* extern "C" { */
+#endif
+#endif /* ____BIG_DECIMAL__H____ */
View
796 lib/ext/bigdecimal/bigdecimal_en.html
@@ -0,0 +1,796 @@
+<!-- saved from url=(0022)http://internet.e-mail -->
+<HTML>
+<HEAD>
+<META HTTP-EQUIV="Content-Type" CONTENT="text/html">
+<style type="text/css"><!--
+body { color: #3f0f0f; background: #fefeff; margin-left: 2em; margin-right: 2em;}
+h1 { color: #ffffff; background-color: #3939AD; border-color: #FF00FF; width: 100%; border-style: solid;
+ border-top-width: 0.1em; border-bottom-width: 0.1em; border-right: none; border-left: none;
+ padding: 0.1em; font-weight: bold; font-size: 160%; text-align: center;}
+h2 { color: #00007f; background-color: #e7e7ff; border-color: #000094; width: 100%; border-style: solid; border-le ft: none; border-right: none; border-top-width: 0.1em; border-bottom-width: 0.1em; padding: 0.1em;
+ font-weight: bold; font-size: 110%;
+}
+h3 { color: #00007f; padding: 0.2em; font-size: 110%;}
+h4, h5 { color: #000000; padding: 0.2em; font-size: 100%;}
+table { margin-top: 0.2em; margin-bottom: 0.2em; margin-left: 2em; margin-right: 2em;}
+caption { color: #7f0000; font-weight: bold;}
+th { background: #e7e7ff; padding-left: 0.2em; padding-right: 0.2em;}
+td { background: #f3f7ff; padding-left: 0.2em; padding-right: 0.2em;}
+code { color: #0000df;}
+dt { margin-top: 0.2em;}
+li { margin-top: 0.2em;}
+pre
+{ BACKGROUND-COLOR: #d0d0d0; BORDER-BOTTOM: medium none; BORDER-LEFT: medium none;
+ BORDER-RIGHT: medium none; BORDER-TOP: medium none; LINE-HEIGHT: 100%; MARGIN: 12px 12px 12px 12px;
+ PADDING-BOTTOM: 12px; PADDING-LEFT: 12px; PADDING-RIGHT: 12px; PADDING-TOP: 12px;
+ WHITE-SPACE: pre; WIDTH: 100%
+}
+--></style>
+
+<TITLE>BigDecimal:An extension library for Ruby</TITLE>
+</HEAD>
+<BODY BGCOLOR=#FFFFE0>
+<H1>BigDecimal(Variable Precision Floating Library for Ruby)</H1>
+<DIV align="right"><A HREF="./bigdecimal_ja.html">Japanese</A></DIV><BR>
+BigDecimal is an extension library for the Ruby interpreter.
+Using BigDecimal class, you can obtain any number of significant digits in computation.
+For the details about Ruby see:<BR>
+<UL>
+<LI><A HREF="http://www.ruby-lang.org/en/">http://www.ruby-lang.org/en/</A>:Official Ruby page(English).</LI>
+<LI><A HREF="http://kahori.com/ruby/ring/">http://kahori.com/ruby/ring/</A>:Mutually linked pages relating to Ruby(Japanese).
+</LI>
+</UL>
+NOTE:<BR>
+ This software is provided "AS IS" and without any express or
+ implied warranties,including,without limitation,the implied
+ warranties of merchantibility and fitness for a particular
+ purpose. For the details,see COPYING and README included in this
+ distribution.
+<BR>
+<hr>
+
+<H2>Contents</H2>
+<UL>
+<LI><A HREF="#INTRO">Introduction</LI>
+<LI><A HREF="#SPEC">Usage and methods</A></LI>
+<LI><A HREF="#UNDEF">Infinity,NaN,Zero</A></LI>
+<LI><A HREF="#STRUCT">Internal structure</A></LI>
+<LI><A HREF="#BASE">Binary or decimal number representation</A></LI>
+<LI><A HREF="#PREC">Resulting number of significant digits</A></LI>
+</UL>
+<HR>
+
+<A NAME="#INTRO">
+<H2>Introduction</H2>
+Ruby already has builtin (variable length integer number) class Bignum. Using Bignum class,you can obtain
+ any integer value in magnitude. But, variable length decimal number class is not yet built in.
+This is why I made variable length floating class BigDecimal.
+Feel free to send any comments or bug reports to me.
+<A HREF="mailto:shigeo@tinyforest.gr.jp">shigeo@tinyforest.gr.jp</A>
+I will try(but can't promise) to fix bugs reported.
+<hr>
+<H2>Installation</H2>
+The Ruby latest version can be downloaded from <A HREF="http://www.ruby-lang.org/en/">Official Ruby page</A>.
+Once decompress the downloaded Ruby archive,follow the normal installation procedures according to the
+documents included.
+
+<A NAME="#SPEC">
+<H2>Usage and methods</H2>
+Suppose you already know Ruby programming,
+to create BigDecimal objects,the program would like:<BR>
+
+<CODE><PRE>
+ require 'bigdecimal'
+ a=BigDecimal::new("0.123456789123456789")
+ b=BigDecimal("123456.78912345678",40)
+ c=a+b
+</PRE></CODE>
+
+<H3>List of methods</H3>
+In 32 bits integer system,every 4 digits(in decimal) are computed simultaneously.
+This means the number of significant digits in BigDecimal is always a multiple of 4.
+<P>
+Some more methods are available in Ruby code (not C code).
+Functions such as sin,cos ...,are in math.rb in bigdecimal directory.
+To use them,require math.rb as:
+<CODE><PRE>
+require "bigdecimal/math.rb"
+</PRE></CODE>
+For details,see the math.rb code and comments.
+Other utility methods are in util.rb.
+To use util.rb, require it as:
+<CODE><PRE>
+require "bigdecimal/util.rb"
+</PRE></CODE>
+For details,see the util.rb code.
+
+<H4><U>Class methods</U></H4>
+<UL>
+<LI><B>new</B></LI><BLOCKQUOTE>
+"new" method creates a new BigDecimal object.<BR>
+a=BigDecimal::new(s[,n]) or<BR>
+a=BigDecimal(s[,n]) or<BR>
+where:<BR>
+s: Initial value string. Spaces will be ignored. Any unrecognizable character for
+representing initial value terminates the string.<BR>
+n: Maximum number of significant digits of a. n must be a Fixnum object.
+If n is omitted or is equal to 0,then the maximum number of significant digits of a is determined from the length of s.
+Actual number of digits handled in computations are usually gretaer than n.<BR>
+n is useful when performing divisions like
+<CODE><PRE>
+BigDecimal("1") / BigDecimal("3") # => 0.3333333333 33E0
+BigDecimal("1",10) / BigDecimal("3",10) # => 0.3333333333 3333333333 33333333E0
+</PRE></CODE>
+but the resulting digits obtained may differ in future version.
+</BLOCKQUOTE>
+
+<LI><B>mode</B></LI><BLOCKQUOTE>
+f = BigDecimal.mode(s[,v])<BR>
+mode method controls BigDecimal computation. If the second argument is not given or is nil,then the value
+of current setting is returned.
+Following usage are defined.<BR>
+<P><B>[EXCEPTION control]</B><P>
+Actions when computation results NaN or Infinity can be defined as follows.
+<P>
+<BLOCKQUOTE>
+f = BigDecimal::mode(BigDecimal::EXCEPTION_NaN,flag)<BR>
+f = BigDecimal::mode(BigDecimal::EXCEPTION_INFINITY,flag)<BR>
+f = BigDecimal::mode(BigDecimal::EXCEPTION_UNDERFLOW,flag)<BR>
+f = BigDecimal::mode(BigDecimal::EXCEPTION_OVERFLOW,flag)<BR>
+f = BigDecimal::mode(BigDecimal::EXCEPTION_ZERODIVIDE,flag)<BR>
+f = BigDecimal::mode(BigDecimal::EXCEPTION_ALL,flag)<BR>
+</BLOCKQUOTE>
+EXCEPTION_NaN controls the execution when computation results to NaN.<BR>
+EXCEPTION_INFINITY controls the execution when computation results to Infinity(}Infinity).<BR>
+EXCEPTION_UNDERFLOW controls the execution when computation underflows.<BR>
+EXCEPTION_OVERFLOW controls the execution when computation overflows.<BR>
+EXCEPTION_ZERODIVIDE controls the execution when zero-division occures.<BR>
+EXCEPTION_ALL controls the execution for any exception defined occures.<BR>
+If the flag is true,then the relating exception is thrown.<BR>
+No exception is thrown when the flag is false(default) and computation
+continues with the result:<BR>
+<BLOCKQUOTE>
+EXCEPTION_NaN results to NaN<BR>
+EXCEPTION_INFINITY results to +Infinity or -Infinity<BR>
+EXCEPTION_UNDERFLOW results to 0.<BR>
+EXCEPTION_OVERFLOW results to +Infinity or -Infinity<BR>
+EXCEPTION_ZERODIVIDE results to +Infinity or -Infinity<BR>
+</BLOCKQUOTE>
+EXCEPTION_INFINITY,EXCEPTION_OVERFLOW, and EXCEPTION_ZERODIVIDE are
+ currently the same.<BR>
+The return value of mode method is the value set.<BR>
+If nil is specified for the second argument,then current setting is returned.<BR>
+Suppose the return value of the mode method is f,then
+ f &amp; BigDecimal::EXCEPTION_NaN !=0 means EXCEPTION_NaN is set to on.
+<P>
+<B>[ROUND error control]</B><P>
+Rounding operation can be controlled as:
+<BLOCKQUOTE>
+f = BigDecimal::mode(BigDecimal::ROUND_MODE,flag)
+</BLOCKQUOTE>
+where flag must be one of:
+<TABLE>
+
+<TR><TD>ROUND_UP</TD><TD>round away from zero.</TD></TR>
+<TR><TD>ROUND_DOWN</TD><TD>round towards zero(truncate).</TD></TR>
+<TR><TD>ROUND_HALF_UP</TD><TD>round up if the digit &gt;= 5 otherwise truncated(default).</TD></TR>
+<TR><TD>ROUND_HALF_DOWN</TD><TD>round up if the digit &gt;= 6 otherwise truncated.</TD></TR>
+<TR><TD>ROUND_HALF_EVEN</TD><TD>round towards the even neighbor(Banker's rounding).
+<TR><TD>ROUND_CEILING</TD><TD>round towards positive infinity(ceil).</TD></TR>
+<TR><TD>ROUND_FLOOR</TD><TD>round towards negative infinity(floor).</TD></TR>
+</TABLE>
+New rounding mode is returned. If nil is specified for the second argument,then current setting is returned.<BR>
+The digit location for rounding operation can not be specified by this mode method,
+use truncate/round/ceil/floor/add/sub/mult/div mthods for each instance instead.
+</BLOCKQUOTE>
+
+<LI><B>limit[(n)]</B></LI><BLOCKQUOTE>
+Limits the maximum digits that the newly created BigDecimal objects can hold never exceed n.
+This means the rounding operation specified by BigDecimal.mode is
+performed if necessary.
+limit returns the value before set if n is nil or is not specified.
+Zero,the default value,means no upper limit.<BR>
+The limit has no more priority than instance methods such as truncate,round,ceil,floor,add,sub,mult,and div. <BR>
+mf = BigDecimal::limit(n)<BR>
+</BLOCKQUOTE>
+
+<LI><B>double_fig</B></LI><BLOCKQUOTE>
+double_fig is a class method which returns the number of digits
+the Float class can have.
+<CODE><PRE>
+ p BigDecimal::double_fig # ==> 20 (depends on the CPU etc.)
+</PRE></CODE>
+The equivalent C programs which calculates the value of
+double_fig is:
+<CODE><PRE>
+ double v = 1.0;
+ int double_fig = 0;
+ while(v + 1.0 > 1.0) {
+ ++double_fig;
+ v /= 10;
+ }
+</PRE></CODE>
+</BLOCKQUOTE>
+
+<LI><B>BASE</B></LI><BLOCKQUOTE>
+Base value used in the BigDecimal calculation.
+On 32 bits integer system,the value of BASE is 10000.<BR>
+b = BigDecimal::BASE<BR>
+</BLOCKQUOTE>
+</UL>
+
+<H4><U>Instance methods</U></H4>
+<UL>
+<LI><B>+</B></LI><BLOCKQUOTE>
+addition(c = a + b)<BR>
+For the resulting number of significant digits of c,see <A HREF="#PREC">Resulting number of significant digits</A>.
+
+</BLOCKQUOTE>
+<LI><B>-</B></LI><BLOCKQUOTE>
+subtraction (c = a - b) or negation (c = -a)<BR>
+For the resulting number of significant digits of c,see <A HREF="#PREC">Resulting number of significant digits</A>.
+
+</BLOCKQUOTE>
+<LI><B>*</B></LI><BLOCKQUOTE>
+multiplication(c = a * b)<BR>
+For the resulting number of significant digits of c,see <A HREF="#PREC">Resulting number of significant digits</A>.
+
+</BLOCKQUOTE>
+<LI><B>/</B></LI><BLOCKQUOTE>
+division(c = a / b)<BR>
+For the resulting number of significant digits of c,see <A HREF="#PREC">Resulting number of significant digits</A>.
+</BLOCKQUOTE>
+
+<LI><B>add(b,n)</B></LI><BLOCKQUOTE>
+c = a.add(b,n)<BR>
+c = a.add(b,n) performs c = a + b.<BR>
+If n is less than the actual significant digits of a + b,
+then c is rounded properly according to the BigDecimal.limit.<BR>
+If n is zero,then the result is the same as +'s.
+</BLOCKQUOTE>
+<LI><B>sub(b,n)</B></LI><BLOCKQUOTE>
+c = a.sub(b,n)<BR>
+c = a.sub(b,n) performs c = a - b.<BR>
+If n is less than the actual significant digits of a - b,
+then c is rounded properly according to the BigDecimal.limit.<BR>
+If n is zero,then the result is the same as -'s.
+
+</BLOCKQUOTE>
+<LI><B>mult(b,n)</B></LI><BLOCKQUOTE>
+c = a.mult(b,n)<BR>
+c = a.mult(b,n) performs c = a * b.<BR>
+If n is less than the actual significant digits of a * b,
+then c is rounded properly according to the BigDecimal.limit.<BR>
+If n is zero,then the result is the same as *'s.
+
+</BLOCKQUOTE>
+<LI><B>div(b[,n])</B></LI><BLOCKQUOTE>
+c = a.div(b,n)<BR>
+c = a.div(b,n) performs c = a / b.<BR>
+If n is less than the actual significant digits of a / b,
+then c is rounded properly according to the BigDecimal.limit.<BR>
+If n is zero,then the result is the same as /'s.
+If n is not given,then the result will be an integer(BigDecimal) like Float#div.
+</BLOCKQUOTE>
+
+<LI><B>fix</B></LI><BLOCKQUOTE>
+c = a.fix<BR>
+returns integer part of a.<BR>
+
+</BLOCKQUOTE>
+<LI><B>frac</B></LI><BLOCKQUOTE>
+c = a.frac<BR>
+returns fraction part of a.<BR>
+
+</BLOCKQUOTE>
+<LI><B>floor[(n)]</B></LI><BLOCKQUOTE>
+c = a.floor<BR>
+returns the maximum integer value (in BigDecimal) which is less than or equal to a.
+<CODE><PRE>
+ c = BigDecimal("1.23456").floor # ==> 1
+ c = BigDecimal("-1.23456").floor # ==> -2
+</PRE></CODE>
+
+As shown in the following example,an optional integer argument (n) specifying the position
+of the target digit can be given.<BR>
+If n> 0,then the (n+1)th digit counted from the decimal point in fraction part is processed(resulting number of fraction part digits is less than or equal to n).<BR>
+If n<0,then the n-th digit counted from the decimal point in integer part is processed(at least n 0's are placed from the decimal point to left).
+<CODE><PRE>
+ c = BigDecimal("1.23456").floor(4) # ==> 1.2345
+ c = BigDecimal("15.23456").floor(-1) # ==> 10.0
+</PRE></CODE>
+
+</BLOCKQUOTE>
+<LI><B>ceil[(n)]</B></LI><BLOCKQUOTE>
+c = a.ceil<BR>
+returns the minimum integer value (in BigDecimal) which is greater than or equal to a.
+<CODE><PRE>
+ c = BigDecimal("1.23456").ceil # ==> 2
+ c = BigDecimal("-1.23456").ceil # ==> -1
+</PRE></CODE>
+
+As shown in the following example,an optional integer argument (n) specifying the position
+of the target digit can be given.<BR>
+If n>0,then the (n+1)th digit counted from the decimal point in fraction part is processed(resulting number of fraction part digits is less than or equal to n).<BR>
+If n<0,then the n-th digit counted from the decimal point in integer part is processed(at least n 0's are placed from the decimal point to left).
+<CODE><PRE>
+ c = BigDecimal("1.23456").ceil(4) # ==> 1.2346
+ c = BigDecimal("15.23456").ceil(-1) # ==> 20.0
+</PRE></CODE>
+
+</BLOCKQUOTE>
+<LI><B>round[(n[,b])]</B></LI><BLOCKQUOTE>
+c = a.round<BR>
+round a to the nearest 1(default)D<BR>
+<CODE><PRE>
+ c = BigDecimal("1.23456").round # ==> 1
+ c = BigDecimal("-1.23456").round # ==> -1
+</PRE></CODE>
+The rounding operation changes according to BigDecimal::mode(BigDecimal::ROUND_MODE,flag) if specified.
+
+As shown in the following example,an optional integer argument (n) specifying the position
+of the target digit can be given.<BR>
+If n>0,then the (n+1)th digit counted from the decimal point in fraction part is processed(resulting number of fraction part digits is less than or equal to n).<BR>
+If n<0,then the n-th digit counted from the decimal point in integer part is processed(at least n 0's are placed from the decimal point to left).
+<CODE><PRE>
+c = BigDecimal::new("1.23456").round(4) # ==> 1.2346
+c = BigDecimal::new("15.23456").round(-1) # ==> 20.0
+</PRE></CODE>
+
+Rounding operation can be specified by setting the second optional argument b with the valid ROUND_MODE.<BR>
+<CODE><PRE>
+c = BigDecimal::new("1.23456").round(3,BigDecimal::ROUND_HALF_EVEN) # ==> 1.234
+c = BigDecimal::new("1.23356").round(3,BigDecimal::ROUND_HALF_EVEN) # ==> 1.234
+</PRE></CODE>
+
+</BLOCKQUOTE>
+<LI><B>truncate[(n)]</B></LI><BLOCKQUOTE>
+c = a.truncate<BR>
+truncate a to the nearest 1D<BR>
+As shown in the following example,an optional integer argument (n) specifying the position
+of the target digit can be given.<BR>
+If n>0,then the (n+1)th digit counted from the decimal point in fraction part is processed(resulting number of fraction part digits is less than or equal to n).<BR>
+If n<0,then the n-th digit counted from the decimal point in integer part is processed(at least n 0's are placed from the decimal point to left).
+
+<CODE><PRE>
+c = BigDecimal::new("1.23456").truncate(4) # ==> 1.2345
+c = BigDecimal::new("15.23456").truncate(-1) # ==> 10.0
+</PRE></CODE>
+</BLOCKQUOTE>
+<LI><B>abs</B></LI><BLOCKQUOTE>
+c = a.abs<BR>
+returns an absolute value of a.<BR>
+
+</BLOCKQUOTE>
+<LI><B>to_i</B></LI><BLOCKQUOTE>
+changes a to an integer.<BR>
+i = a.to_i<BR>
+i becomes to Fixnum or Bignum.
+If a is Infinity or NaN,then i becomes to nil.
+
+</BLOCKQUOTE>
+<LI><B>to_s[(n)]</B></LI><BLOCKQUOTE>
+converts to string(default results look like "0.xxxxxEn").
+<CODE><PRE>
+BigDecimal("1.23456").to_s # ==> "0.123456E1"
+</PRE></CODE>
+If n(>0) is given,then a space is inserted to each of two parts divided by the decimal point
+after every n digits for readability.
+<CODE><PRE>
+BigDecimal("0.1234567890123456789").to_s(10) # ==> "0.1234567890 123456789E0"
+</PRE></CODE>
+n can be a string representing a positive integer number.
+<CODE><PRE>
+BigDecimal("0.1234567890123456789").to_s("10") # ==> "0.1234567890 123456789E0"
+</PRE></CODE>
+If the first character is '+'(or ' '),then '+'(or ' ') will be set before value string
+when the value is positive.
+<CODE><PRE>
+BigDecimal("0.1234567890123456789").to_s(" 10") # ==> " 0.1234567890 123456789E0"
+BigDecimal("0.1234567890123456789").to_s("+10") # ==> "+0.1234567890 123456789E0"
+BigDecimal("-0.1234567890123456789").to_s("10") # ==> "-0.1234567890 123456789E0"
+</PRE></CODE>
+
+At the end of the string,'E'(or 'e') or 'F'(or 'f') can be specified to change
+number representation.
+<CODE><PRE>
+BigDecimal("1234567890.123456789").to_s("E") # ==> "0.1234567890123456789E10"
+BigDecimal("1234567890.123456789").to_s("F") # ==> "1234567890.123456789"
+BigDecimal("1234567890.123456789").to_s("5E") # ==> "0.12345 67890 12345 6789E10"
+BigDecimal("1234567890.123456789").to_s("5F") # ==> "12345 67890.12345 6789"
+</PRE></CODE>
+
+</BLOCKQUOTE>
+<LI><B>exponent</B></LI><BLOCKQUOTE>
+returns an integer holding exponent value of a.<BR>
+n = a.exponent <BR>
+means a = 0.xxxxxxx*10**n.
+</BLOCKQUOTE>
+
+<LI><B>precs</B></LI><BLOCKQUOTE>
+n,m = a.precs <BR>
+prec returns number of significant digits (n) and maximum number of
+significant digits (m) of a.
+</BLOCKQUOTE>
+
+<LI><B>to_f</B></LI><BLOCKQUOTE>
+Creates a new Float object having (nearly) the same value.
+Use split method if you want to convert by yourself.
+</BLOCKQUOTE>
+
+</BLOCKQUOTE>
+<LI><B>sign</B></LI><BLOCKQUOTE>
+n = a.sign <BR>
+returns positive value if a &gt; 0,negative value if a &lt; 0,
+otherwise zero if a == 0.<BR>
+where the value of n means that a is:<BR>
+n = BigDecimal::SIGN_NaN(0) : a is NaN<BR>
+n = BigDecimal::SIGN_POSITIVE_ZERO(1) : a is +0<BR>
+n = BigDecimal::SIGN_NEGATIVE_ZERO(-1) : a is -0<BR>
+n = BigDecimal::SIGN_POSITIVE_FINITE(2) : a is positive<BR>
+n = BigDecimal::SIGN_NEGATIVE_FINITE(-2) : a is negative<BR>
+n = BigDecimal::SIGN_POSITIVE_INFINITE(3) : a is +Infinity<BR>
+n = BigDecimal::SIGN_NEGATIVE_INFINITE(-3) : a is -Infinity<BR>
+The value in () is the actual value,see (<A HREF="#STRUCT">Internal structure</A>.<BR>
+
+</BLOCKQUOTE>
+<LI><B>nan?</B></LI><BLOCKQUOTE>
+a.nan? returns True when a is NaN.
+
+</BLOCKQUOTE>
+<LI><B>infinite?</B></LI><BLOCKQUOTE>
+a.infinite? returns 1 when a is +‡,-1 when a is -‡, nil otherwise.
+
+</BLOCKQUOTE>
+<LI><B>finite?</B></LI><BLOCKQUOTE>
+a.finite? returns true when a is neither ‡ nor NaN.
+</BLOCKQUOTE>
+
+<LI><B>zero?</B></LI><BLOCKQUOTE>
+c = a.zero?<BR>
+returns true if a is equal to 0,otherwise returns false<BR>
+</BLOCKQUOTE>
+<LI><B>nonzero?</B></LI><BLOCKQUOTE>
+c = a.nonzero?<BR>
+returns nil if a is 0,otherwise returns a itself.<BR>
+</BLOCKQUOTE>
+
+<LI><B>split</B></LI><BLOCKQUOTE>
+decomposes a BigDecimal value to 4 parts.
+All 4 parts are returned as an array.<BR>
+Parts consist of a sign(0 when the value is NaN,+1 for positive and
+ -1 for negative value), a string representing fraction part,base value(always 10 currently),and an integer(Fixnum) for exponent respectively.
+a=BigDecimal::new("3.14159265")<BR>
+f,x,y,z = a.split<BR>
+where f=+1,x="314159265",y=10 and z=1<BR>
+therefore,you can translate BigDecimal value to Float as:<BR>
+s = "0."+x<BR>
+b = f*(s.to_f)*(y**z)<BR>
+
+</BLOCKQUOTE>
+<LI><B>inspect</B></LI><BLOCKQUOTE>
+is used for debugging output.<BR>
+p a=BigDecimal::new("3.14",10)<BR>
+should produce output like "#&lt;0x112344:'0.314E1',4(12)%gt;".
+where "0x112344" is the address,
+'0.314E1' is the value,4 is the number of the significant digits,
+and 12 is the maximum number of the significant digits
+the object can hold.
+</BLOCKQUOTE>
+
+<LI><B>sqrt</B></LI><BLOCKQUOTE>
+c = a.sqrt(n)<BR>
+computes square root value of a with significant digit number n at least.<BR>
+</BLOCKQUOTE>
+
+<LI><B>**</B></LI><BLOCKQUOTE>
+c = a ** n<BR>
+returns the value of a powered by n.
+n must be an integer.<BR>
+
+</BLOCKQUOTE>
+<LI><B>power</B></LI><BLOCKQUOTE>
+The same as ** method.<BR>
+c = a.power(n)<BR>
+returns the value of a powered by n(c=a**n).
+n must be an integer.<BR>
+</BLOCKQUOTE>
+
+<LI><B>divmod,quo,modulo,%,remainder</B></LI><BLOCKQUOTE>
+See,corresponding methods in Float class.
+</BLOCKQUOTE>
+
+</BLOCKQUOTE>
+<LI><B>&lt;=&gt;</B></LI><BLOCKQUOTE>
+c = a &lt;=&gt; b <BR>
+returns 0 if a==b,1 if a &gt b,and returns -1 if a &lt b.<BR>
+</BLOCKQUOTE>
+</UL>
+
+Following methods need no explanation.<BR>
+<UL>
+<LI>==</LI>
+<LI>===</LI>
+same as ==,used in case statement.
+<LI>!=</LI>
+<LI>&lt;</LI>
+<LI>&lt;=</LI>
+<LI>&gt;</LI>
+<LI>&gt;=</LI>
+</UL>
+
+<HR>
+<H3>About 'coerce'</H3>
+<B>For the binary operation like A op B:</B>
+<DL>
+<DT> 1.Both A and B are BigDecimal objects</DT>
+<DD> A op B is normally performed.</DD>
+<DT> 2.A is the BigDecimal object but B is other than BigDecimal object</DT>
+<DD> Operation is performed,after B is translated to correcponding BigDecimal object(because BigDecimal supports coerce method).</DD>
+<DT> 3.A is not the BigDecimal object but B is BigDecimal object</DT>
+<DD>If A has coerce mthod,then B will translate A to corresponding
+BigDecimal object and the operation is performed,otherwise an error occures.</DD>
+</DL>
+
+String is not translated to BigDecimal in default.
+Uncomment /* #define ENABLE_NUMERIC_STRING */ in bigdecimal.c, compile and install
+again if you want to enable string to BigDecimal conversion.
+Translation stops without error at the character representing non digit.
+For instance,"10XX" is translated to 10,"XXXX" is translated to 0.<BR>
+String representing zero or infinity such as "Infinity","+Infinity","-Infinity",and "NaN" can also be translated to BigDecimal unless false is specified by mode method.<BR>
+
+BigDecimal class supports coerce method(for the details about coerce method,see Ruby documentations). This means the most binary operation can be performed if the BigDecimal object is at the left hand side of the operation.<BR><BR>
+
+ For example:
+<CODE><PRE>
+ a = BigDecimal.E(20)
+ c = a * "0.123456789123456789123456789" # A String is changed to BigDecimal object.
+</PRE></CODE>
+is performed normally.<BR>
+ But,because String does not have coerce method,the following example can not be performed.<BR>
+
+<CODE><PRE>
+ a = BigDecimal.E(20)
+ c = "0.123456789123456789123456789" * a # ERROR
+</PRE></CODE>
+
+If you actually have any inconvenience about the error above.
+You can define a new class derived from String class,
+and define coerce method within the new class.<BR>
+
+<hr>
+<A NAME="#UNDEF">
+<H2>Infinity,Not a Number(NaN),Zero</H2>
+Infinite numbers and NaN can be represented by string writing "+Infinity"(or "Infinity"),"-Infinity",and "NaN" respectively in your program.
+Infinite numbers can be obtained by 1.0/0.0(=Infinity) or -1.0/0.0(=-Infinity).
+<BR><BR>
+NaN(Not a number) can be obtained by undefined computation like 0.0/0.0
+or Infinity-Infinity.
+Any computation including NaN results to NaN.
+Comparisons with NaN never become true,including comparison with NaN itself.
+<BR><BR>
+Zero has two different variations as +0.0 and -0.0.
+But,still, +0.0==-0.0 is true.
+<BR><BR>
+Computation results including Infinity,NaN,+0.0 or -0.0 become complicated.
+Run following program and comfirm the results.
+Send me any incorrect result if you find.
+
+<CODE><PRE>
+ require "bigdecimal"
+ aa = %w(1 -1 +0.0 -0.0 +Infinity -Infinity NaN)
+ ba = %w(1 -1 +0.0 -0.0 +Infinity -Infinity NaN)
+ opa = %w(+ - * / <=> > >= < == != <=)
+ for a in aa
+ for b in ba
+ for op in opa
+ x = BigDecimal::new(a)
+ y = BigDecimal::new(b)
+ eval("ans= x #{op} y;print a,' ',op,' ',b,' ==> ',ans.to_s,\"\n\"")
+ end
+ end
+ end
+</PRE></CODE>
+<hr>
+
+<A NAME="#STRUCT">
+<H2>Internal structure</H2>
+BigDecimal number is defined by the structure Real in BigDecimal.h.
+Digits representing a float number are kept in the array frac[] defined in the structure.
+In the program,any floating number(BigDecimal number) is represented as:<BR>
+ <BigDecimal number> = 0.xxxxxxxxx*BASE**n<BR><BR>
+where 'x' is any digit representing mantissa(kept in the array frac[]),
+BASE is base value(=10000 in 32 bit integer system),
+and n is the exponent value.<BR>
+Larger BASE value enables smaller size of the array frac[],and increases computation speed.
+The value of BASE is defined ind VpInit(). In 32 bit integer system,this value is
+10000. In 64 bit integer system,the value becomes larger.
+BigDecimal has not yet been compiled and tested on 64 bit integer system.
+It will be very nice if anyone try to run BigDecimal on 64 bit system and
+ inform me the results.
+When BASE is 10000,an element of the array frac[] can have vale of from 0 to 9999.
+(up to 4 digits).<BR>
+The structure Real is defined in bigdecimal.h as:<BR>
+<CODE><PRE>
+ typedef struct {
+ VALUE obj; /* Back pointer(VALUE) for Ruby object. */
+ unsigned long MaxPrec; /* The size of the array frac[] */
+ unsigned long Prec; /* Current size of frac[] actually used. */
+ short sign; /* Attribute of the value. */
+ /* ==0 : NaN */
+ /* 1 : +0 */
+ /* -1 : -0 */
+ /* 2 : Positive number */
+ /* -2 : Negative number */
+ /* 3 : +Infinity */
+ /* -3 : -Infinity */
+ unsigned short flag; /* Control flag */
+ int exponent; /* Exponent value(0.xxxx*BASE**exponent) */
+ unsigned long frac[1]; /* An araay holding mantissa(Variable) */
+ } Real;
+</CODE></PRE>
+The decimal value 1234.56784321 is represented as(BASE=10000):<BR>
+<PRE>
+ 0.1234 5678 4321*(10000)**1
+</PRE>
+where frac[0]=1234,frac[1]=5678,frac[2]=4321,
+Prec=3,sign=2,exponent=1. MaxPrec can be any value greater than or equal to
+Prec.
+<hr>
+
+<A NAME="#BASE">
+<H2>Binary or decimal number representation</H2>
+I adopted decimal number representation for BigDecimal implementation.
+Of cource,binary number representation is common on the most computers.
+
+<H3>Advantages using decimal representation</H3>
+The reason why I adopted decimal number representation for BigDecimal is:<BR>
+<DL>
+<DT>Easy for debugging
+<DD>The floating number 1234.56784321 can be easily represented as:<BR>
+ frac[0]=1234,frac[1]=5678,frac[2]=4321,exponent=1,and sign=2.
+<DT>Exact representation
+<DD>Following program can add all numbers(in decimal) in a file
+ without any error(no round operation).<BR>
+
+<CODE><PRE>
+ file = File::open(....,"r")
+ s = BigDecimal::new("0")
+ while line = file.gets
+ s = s + line
+ end
+</PRE></CODE>
+
+If the internal representation is binary,translation from decimal to
+binary is required and the translation error is inevitable.
+For example, 0.1 can not exactly be represented in binary.<BR>
+0.1 => b1*2**(-1)+b1*2**(-2)+b3*2**(-3)+b4*2**(-4)....<BR>
+where b1=0,b2=0,b3=0,b4=1...<BR>
+bn(n=1,2,3,...) is infinite series of digit with value of 0 or 1,
+and rounding operation is necessary but where we should round the series ?
+Of cource,exact "0.1" is printed if the rouding operation is properly done,
+<DT>Significant digit we can have is automatically determined
+<DD>In binary representation,0.1 can not be represented in finite series of digit.
+
+But we only need one element(frac[0]=1) in decimal representation.
+This means that we can always determine the size of the array frac[] in Real
+structure.
+</DL>
+
+<H3>Disadvantage of decimal representation</H3>
+Because most computers have no internal decimal representaion.
+Once you use BigDecimal,you need to keep using it without
+considering computation cost if exact computation is required.
+
+<H4>Which is the first input?</H4>
+Because most people uses decimal notatin for numeric data representation,
+BigDecimal can handle numeric data without loss of translation error.
+<hr>
+
+<A NAME="#PREC">
+<H2>Resulting number of significant digits</H2>
+For the fundamental arithmetics such as addition,subtraction,
+multiplication,and division,I prepared 2 group of methods<BR>
+
+<H3>1. +,-,*,/</H3>
+For the operation + - * /,you can not specify the resulting
+number of significant digits.<BR>
+Resulting number of significant digits are defined as:<BR>
+1.1 For *,resulting number of significant digits is the sum of the
+significant digits of both side of the operator. For / ,resulting number of significant digits is the sum of the
+maximum significant digits of both side of the operator.<BR>
+1.2 For + and -,resulting number of significant digits is determined so that
+ no round operation is needed. <br>
+For example, c has more than 100 siginificant digits if c is computed as:<BR>
+c = 0.1+0.1*10**(-100)<br>
+<BR>
+As +,-,and * are always exact(no round operation is performed unless BigDecimal.limit is specified),
+which means more momories are required to keep computation results.
+But,the division such as c=1.0/3.0 will always be rounded.<BR>
+
+<H3>2. add,sub,mult,div</H3>
+The length of the significant digits obtained from +,-,*,/
+is always defined by that of right and left side of the operator.
+To specify the length of the significant digits by your self,
+use methos add,sub,mult,div.
+<CODE><PRE>
+ BigDecimal("2").div(3,12) # 2.0/3.0 => 0.6666666666 67E0
+</PRE></CODE>
+</BLOCKQUOTE>
+
+<H3>3. truncate,round,ceil,floor</H3>
+Using these methods,you can specify rounding location relatively from
+decimal point.
+<CODE><PRE>
+ BigDecimal("6.66666666666666").round(12) # => 0.6666666666 667E1
+</PRE></CODE>
+</BLOCKQUOTE>
+
+
+<H3>4. Example</H3>
+Following example compute the ratio of the circumference of a circle to
+its dirmeter(pi=3.14159265358979....) using J.Machin's formula.
+<BR><BR>
+<CODE><PRE>
+#!/usr/local/bin/ruby
+
+require "bigdecimal"
+#
+# Calculates 3.1415.... (the number of times that a circle's diameter
+# will fit around the circle) using J. Machin's formula.
+#
+def big_pi(sig) # sig: Number of significant figures
+ exp = -sig
+ pi = BigDecimal::new("0")
+ two = BigDecimal::new("2")
+ m25 = BigDecimal::new("-0.04")
+ m57121 = BigDecimal::new("-57121")
+
+ u = BigDecimal::new("1")
+ k = BigDecimal::new("1")
+ w = BigDecimal::new("1")
+ t = BigDecimal::new("-80")
+ while (u.nonzero? && u.exponent >= exp)
+ t = t*m25
+ u = t.div(k,sig)
+ pi = pi + u
+ k = k+two
+ end
+
+ u = BigDecimal::new("1")
+ k = BigDecimal::new("1")
+ w = BigDecimal::new("1")
+ t = BigDecimal::new("956")
+ while (u.nonzero? && u.exponent >= exp )
+ t = t.div(m57121,sig)
+ u = t.div(k,sig)
+ pi = pi + u
+ k = k+two
+ end
+ pi
+end
+
+if $0 == __FILE__
+ if ARGV.size == 1
+ print "PI("+ARGV[0]+"):\n"
+ p big_pi(ARGV[0].to_i)
+ else
+ print "TRY: ruby pi.rb 1000 \n"
+ end
+end
+
+</PRE></CODE>
+<HR>
+<FONT size=2>
+<I>
+<A HREF="http://www.tinyforest.gr.jp">
+Shigeo Kobayashi
+</A>
+(E-Mail:<A HREF="mailto:shigeo@tinyforest.gr.jp">&lt;shigeo@tinyforest.gr.jp&gt;</U></A>)
+</I>
+</FONT>
+</TD>
+</TR>
+</TABLE>
+</BODY>
+</HTML>
View
799 lib/ext/bigdecimal/bigdecimal_ja.html
@@ -0,0 +1,799 @@
+<!-- saved from url=(0022)http://internet.e-mail -->
+<HTML>
+<HEAD>
+<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=Shift_JIS">
+<style type="text/css"><!--
+body { color: #3f0f0f; background: #fefeff; margin-left: 2em; margin-right: 2em;}
+h1 { color: #ffffff; background-color: #3939AD; border-color: #FF00FF; width: 100%;
+ border-style: solid; border-top-width: 0.1em; border-bottom-width: 0.1em; border-right: none;
+ border-left: none; padding: 0.1em; font-weight: bold; font-size: 160%; text-align: center;
+}
+h2 { color: #00007f; background-color: #e7e7ff; border-color: #000094; width: 100%;
+ border-style: solid; border-left: none; border-right: none; border-top-width: 0.1em; border-bottom-width: 0.1em;
+ padding: 0.1em;
+ font-weight: bold; font-size: 110%;
+}
+h3 { color: #00007f; padding: 0.2em; font-size: 110%;}
+h4, h5 { color: #000000; padding: 0.2em; font-size: 100%;}
+table { margin-top: 0.2em; margin-bottom: 0.2em; margin-left: 2em; margin-right: 2em;}
+caption { color: #7f0000; font-weight: bold;}
+th { background: #e7e7ff; padding-left: 0.2em; padding-right: 0.2em;}
+td { background: #f3f7ff; padding-left: 0.2em; padding-right: 0.2em;}
+code { color: #0000df;}
+dt { margin-top: 0.2em;}
+li { margin-top: 0.2em;}
+pre
+{ BACKGROUND-COLOR: #d0d0d0; BORDER-BOTTOM: medium none; BORDER-LEFT: medium none;
+ BORDER-RIGHT: medium none; BORDER-TOP: medium none; LINE-HEIGHT: 100%; MARGIN: 12px 12px 12px 12px;
+ PADDING-BOTTOM: 12px; PADDING-LEFT: 12px; PADDING-RIGHT: 12px; PADDING-TOP: 12px;
+ WHITE-SPACE: pre; WIDTH: 100%
+}
+--></style>
+
+<TITLE>BigDecimal:An extension library for Ruby</TITLE>
+</HEAD>
+<BODY BGCOLOR=#FFFFE0>
+<H1>BigDecimal(可変長浮動少数点演算用拡張ライブラリ)</H1>
+<DIV align="right"><A HREF="./bigdecimal_en.html">English</A></DIV><BR>
+BigDecimal はオブジェクト指向の強力なスクリプト言語である Ruby に可変長浮動小数点
+計算機能を追加するための拡張ライブラリです。
+Ruby についての詳しい内容は以下のURLを参照してください。
+<UL>
+<LI><A HREF="http://www.ruby-lang.org/ja/">http://www.ruby-lang.org/ja/</A>:Ruby公式ページ</LI>
+<LI><A HREF="http://kahori.com/ruby/ring/">http://kahori.com/ruby/ring/</A>:Rubyに関するページを辿れます</LI>
+</UL>
+<hr>
+<H2>目次</H2>
+<UL>
+<LI><A HREF="#INTRO">はじめに</LI>
+<LI><A HREF="#SPEC">使用方法とメソッドの一覧</A></LI>
+<LI><A HREF="#UNDEF">無限、非数、ゼロの扱い</A></LI>
+<LI><A HREF="#STRUCT">内部構造</A></LI>
+<LI><A HREF="#BASE">2進と10進</A></LI>
+<LI><A HREF="#PREC">計算精度について</A></LI>
+</UL>
+
+<HR>
+<A NAME="#INTRO">
+<H2>はじめに</H2>
+Ruby には Bignum というクラスがあり、数百桁の整数でも計算することができます。
+ただ、任意桁の浮動少数点演算用クラスが無いようです。そこで、
+任意桁の浮動少数点演算用拡張ライブラリ BigDecimal を作成しました。
+不具合や助言・提案がある場合どしどし、
+<A HREF="mailto:shigeo@tinyforest.gr.jp">shigeo@tinyforest.gr.jp</A>
+までお知らせください。不具合を直す気は大いにあります。ただ、時間などの関係で約束
+はできません。また、結果についても保証できるものではありません。
+予め、ご了承ください。
+<BR><BR>
+このプログラムは、自由に配布・改変して構いません。ただし、著作権は放棄していません。
+配布・改変等の権利は Ruby のそれに準じます。詳しくは README を読んでください。
+
+<hr>
+<H2>インストールについて</H2>
+BigDecimal を含む Ruby の最新版は<A HREF="http://www.ruby-lang.org/ja/">Ruby公式ページ</A>からダウンロードできます。
+ダウンロードした最新版を解凍したら、通常のインストール手順を実行して下さい。
+Ruby が正しくインストールされれば、同時に BigDecimal も利用できるようになるはずです。
+ソースファイルは
+bigdecimal.c,bigdecimal.h
+の2個のみです。<BR>
+
+<hr>
+<A NAME="#SPEC">
+<H2>使用方法とメソッドの一覧</H2>
+「Rubyは既に書ける」という前提で、
+<CODE><PRE>
+require 'bigdecimal'
+a=BigDecimal::new("0.123456789123456789")
+b=BigDecimal("123456.78912345678",40)
+c=a+b
+</PRE></CODE>
+<br>
+というような感じで使用します。
+
+<H3>メソッド一覧</H3>
+以下のメソッドが利用可能です。
+「有効桁数」とは BigDecimal が精度を保証する桁数です。
+ぴったりではありません、若干の余裕を持って計算されます。
+また、例えば32ビットのシステムでは10進で4桁毎に計算します。従って、現状では、
+内部の「有効桁数」は4の倍数となっています。
+<P>
+以下のメソッド以外にも、(C ではない) Ruby ソースの形で
+提供されているものもあります。例えば、
+<CODE><PRE>
+require "bigdecimal/math.rb"
+</PRE></CODE>
+とすることで、sin や cos といった関数が使用できるようになります。
+使用方法など、詳細は math.rb の内容を参照して下さい。
+
+その他、Float との相互変換などのメソッドが util.rb でサポートされています。
+利用するには
+<CODE><PRE>
+require "bigdecimal/util.rb"
+</PRE></CODE>
+のようにします。詳細は util.rb の内容を参照して下さい。
+
+<H4><U>クラスメソッド</U></H4>
+<UL>
+<LI><B>new</B></LI><BLOCKQUOTE>
+新しい BigDecimal オブジェクトを生成します。<BR>
+a=BigDecimal::new(s[,n]) または<BR>
+a=BigDecimal(s[,n])<BR>
+s は数字を表現する初期値を文字列で指定します。
+スペースは無視されます。また、判断できない文字が出現した時点で
+文字列は終了したものとみなされます。
+n は必要な有効桁数(a の最大有効桁数)を整数で指定します。
+n が 0 または省略されたときは、n の値は s の有効桁数とみなされます。
+s の有効桁数より n が小さいときも n=0 のときと同じです。
+a の最大有効桁