# $Release Version: 0.5 $
# $Revision: 1.1.1.1.4.1 $
# mathn serves to make mathematical operations more precise in Ruby
# and to integrate other mathematical standard libraries.
# 3 / 2 => 3/2 # Rational
# mathn keeps value in exact terms.
# 20 / 9 * 3 * 14 / 7 * 3 / 2 # => 18
# 20 / 9 * 3 * 14 / 7 * 3 / 2 # => 20
# When you require 'mathn', the libraries for Prime, CMath, Matrix and Vector
# Author: Keiju ISHITSUKA (SHL Japan Inc.)
# class Numeric follows to make this documentation findable in a reasonable
warn('lib/mathn.rb is deprecated') if $VERBOSE
unless defined?(Math.exp!)
Object.instance_eval{remove_const :Math}
# When mathn is required, Fixnum's division is enhanced to
# return more precise values from mathematical expressions.
# +/+ defines the Rational division for Fixnum.
# When mathn is required Bignum's division is enhanced to
# return more precise values from mathematical expressions.
# (2**72) / ((2**70) * 3) # => 4/3
# +/+ defines the Rational division for Bignum.
# (2**72) / ((2**70) * 3) # => 4/3
# When mathn is required, the Math module changes as follows:
# Standard Math module behaviour:
# Math.sqrt(4/9) # => 0.0
# Math.sqrt(4.0/9.0) # => 0.666666666666667
# Math.sqrt(- 4/9) # => Errno::EDOM: Numerical argument out of domain - sqrt
# After require 'mathn', this is changed to:
# Math.sqrt(4/9) # => 2/3
# Math.sqrt(4.0/9.0) # => 0.666666666666667
# Math.sqrt(- 4/9) # => Complex(0, 2/3)
# Computes the square root of +a+. It makes use of Complex and
# Rational to have no rounding errors if possible.
# Math.sqrt(4/9) # => 2/3
# Math.sqrt(- 4/9) # => Complex(0, 2/3)
# Math.sqrt(4.0/9.0) # => 0.666666666666667
abs = sqrt(a.real*a.real + a.imag*a.imag)
x = sqrt((a.real + abs)/Rational(2))
y = sqrt((-a.real + abs)/Rational(2))
elsif a.respond_to?(:nan?) and a.nan?
# Compute square root of a non negative number. This method is
# internally used by +Math.sqrt+.
elsif a.kind_of?(Rational)
rsqrt(a.numerator)/rsqrt(a.denominator)
byte_a = [src & 0xffffffff]
while (src >= max) and (src >>= 32)
byte_a.unshift src & 0xffffffff
main = (main << 32) + elm
if main * 4 < side * side
applo = ((sqrt!(side * side + 4 * main) - side)/2.0).to_i + 1
applo = sqrt!(main).to_i + 1
while (x = (side + applo) * applo) > main
answer = (answer << 16) + applo