require 'bigdecimal'
a=BigDecimal::new("0.123456789123456789")
b=BigDecimal("123456.78912345678",40)
c=a+b
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:
For details,see the math.rb code and comments.
Other utility methods are in util.rb.
To use util.rb, require it as:
require "bigdecimal/math.rb"
For details,see the util.rb code.
require "bigdecimal/util.rb"
"new" method creates a new BigDecimal object.
a=BigDecimal::new(s[,n]) or
a=BigDecimal(s[,n]) or
where:
s: Initial value string. Spaces will be ignored. Any unrecognizable character for representing initial value terminates the string.
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.
n is useful when performing divisions likebut the resulting digits obtained may differ in future version.
BigDecimal("1") / BigDecimal("3") # => 0.3333333333 33E0 BigDecimal("1",10) / BigDecimal("3",10) # => 0.3333333333 3333333333 33333333E0
f = BigDecimal.mode(s[,v])
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.
[EXCEPTION control]
Actions when computation results NaN or Infinity can be defined as follows.
f = BigDecimal::mode(BigDecimal::EXCEPTION_NaN,flag)EXCEPTION_NaN controls the execution when computation results to NaN.
f = BigDecimal::mode(BigDecimal::EXCEPTION_INFINITY,flag)
f = BigDecimal::mode(BigDecimal::EXCEPTION_UNDERFLOW,flag)
f = BigDecimal::mode(BigDecimal::EXCEPTION_OVERFLOW,flag)
f = BigDecimal::mode(BigDecimal::EXCEPTION_ZERODIVIDE,flag)
f = BigDecimal::mode(BigDecimal::EXCEPTION_ALL,flag)
EXCEPTION_INFINITY controls the execution when computation results to Infinity(}Infinity).
EXCEPTION_UNDERFLOW controls the execution when computation underflows.
EXCEPTION_OVERFLOW controls the execution when computation overflows.
EXCEPTION_ZERODIVIDE controls the execution when zero-division occures.
EXCEPTION_ALL controls the execution for any exception defined occures.
If the flag is true,then the relating exception is thrown.
No exception is thrown when the flag is false(default) and computation continues with the result:
EXCEPTION_NaN results to NaNEXCEPTION_INFINITY,EXCEPTION_OVERFLOW, and EXCEPTION_ZERODIVIDE are currently the same.
EXCEPTION_INFINITY results to +Infinity or -Infinity
EXCEPTION_UNDERFLOW results to 0.
EXCEPTION_OVERFLOW results to +Infinity or -Infinity
EXCEPTION_ZERODIVIDE results to +Infinity or -Infinity
The return value of mode method is the value set.
If nil is specified for the second argument,then current setting is returned.
Suppose the return value of the mode method is f,then f & BigDecimal::EXCEPTION_NaN !=0 means EXCEPTION_NaN is set to on.[ROUND error control]
Rounding operation can be controlled as:
f = BigDecimal::mode(BigDecimal::ROUND_MODE,flag)where flag must be one of:New rounding mode is returned. If nil is specified for the second argument,then current setting is returned.
ROUND_UP round away from zero. ROUND_DOWN round towards zero(truncate). ROUND_HALF_UP round up if the digit >= 5 otherwise truncated(default). ROUND_HALF_DOWN round up if the digit >= 6 otherwise truncated. ROUND_HALF_EVEN round towards the even neighbor(Banker's rounding). ROUND_CEILING round towards positive infinity(ceil). ROUND_FLOOR round towards negative infinity(floor).
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.
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.
The limit has no more priority than instance methods such as truncate,round,ceil,floor,add,sub,mult,and div.
mf = BigDecimal::limit(n)
double_fig is a class method which returns the number of digits the Float class can have.The equivalent C programs which calculates the value of double_fig is:
p BigDecimal::double_fig # ==> 20 (depends on the CPU etc.)
double v = 1.0; int double_fig = 0; while(v + 1.0 > 1.0) { ++double_fig; v /= 10; }
Base value used in the BigDecimal calculation. On 32 bits integer system,the value of BASE is 10000.
b = BigDecimal::BASE
addition(c = a + b)
For the resulting number of significant digits of c,see Resulting number of significant digits.
subtraction (c = a - b) or negation (c = -a)
For the resulting number of significant digits of c,see Resulting number of significant digits.
multiplication(c = a * b)
For the resulting number of significant digits of c,see Resulting number of significant digits.
division(c = a / b)
For the resulting number of significant digits of c,see Resulting number of significant digits.
c = a.add(b,n)
c = a.add(b,n) performs c = a + b.
If n is less than the actual significant digits of a + b, then c is rounded properly according to the BigDecimal.limit.
If n is zero,then the result is the same as +'s.
c = a.sub(b,n)
c = a.sub(b,n) performs c = a - b.
If n is less than the actual significant digits of a - b, then c is rounded properly according to the BigDecimal.limit.
If n is zero,then the result is the same as -'s.
c = a.mult(b,n)
c = a.mult(b,n) performs c = a * b.
If n is less than the actual significant digits of a * b, then c is rounded properly according to the BigDecimal.limit.
If n is zero,then the result is the same as *'s.
c = a.div(b,n)
c = a.div(b,n) performs c = a / b.
If n is less than the actual significant digits of a / b, then c is rounded properly according to the BigDecimal.limit.
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.
c = a.fix
returns integer part of a.
c = a.frac
returns fraction part of a.
c = a.floor
returns the maximum integer value (in BigDecimal) which is less than or equal to a.As shown in the following example,an optional integer argument (n) specifying the position of the target digit can be given.
c = BigDecimal("1.23456").floor # ==> 1 c = BigDecimal("-1.23456").floor # ==> -2
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).
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).
c = BigDecimal("1.23456").floor(4) # ==> 1.2345 c = BigDecimal("15.23456").floor(-1) # ==> 10.0
c = a.ceil
returns the minimum integer value (in BigDecimal) which is greater than or equal to a.As shown in the following example,an optional integer argument (n) specifying the position of the target digit can be given.
c = BigDecimal("1.23456").ceil # ==> 2 c = BigDecimal("-1.23456").ceil # ==> -1
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).
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).
c = BigDecimal("1.23456").ceil(4) # ==> 1.2346 c = BigDecimal("15.23456").ceil(-1) # ==> 20.0
c = a.round
round a to the nearest 1(default)D
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.
c = BigDecimal("1.23456").round # ==> 1 c = BigDecimal("-1.23456").round # ==> -1
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).
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).Rounding operation can be specified by setting the second optional argument b with the valid ROUND_MODE.
c = BigDecimal::new("1.23456").round(4) # ==> 1.2346 c = BigDecimal::new("15.23456").round(-1) # ==> 20.0
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
c = a.truncate
truncate a to the nearest 1D
As shown in the following example,an optional integer argument (n) specifying the position of the target digit can be given.
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).
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).
c = BigDecimal::new("1.23456").truncate(4) # ==> 1.2345 c = BigDecimal::new("15.23456").truncate(-1) # ==> 10.0
c = a.abs
returns an absolute value of a.
changes a to an integer.
i = a.to_i
i becomes to Fixnum or Bignum. If a is Infinity or NaN,then i becomes to nil.
converts to string(default results look like "0.xxxxxEn").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.
BigDecimal("1.23456").to_s # ==> "0.123456E1"n can be a string representing a positive integer number.
BigDecimal("0.1234567890123456789").to_s(10) # ==> "0.1234567890 123456789E0"If the first character is '+'(or ' '),then '+'(or ' ') will be set before value string when the value is positive.
BigDecimal("0.1234567890123456789").to_s("10") # ==> "0.1234567890 123456789E0"At the end of the string,'E'(or 'e') or 'F'(or 'f') can be specified to change number representation.
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"
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"
returns an integer holding exponent value of a.
n = a.exponent
means a = 0.xxxxxxx*10**n.
n,m = a.precs
prec returns number of significant digits (n) and maximum number of significant digits (m) of a.
Creates a new Float object having (nearly) the same value. Use split method if you want to convert by yourself.
n = a.sign
returns positive value if a > 0,negative value if a < 0, otherwise zero if a == 0.
where the value of n means that a is:
n = BigDecimal::SIGN_NaN(0) : a is NaN
n = BigDecimal::SIGN_POSITIVE_ZERO(1) : a is +0
n = BigDecimal::SIGN_NEGATIVE_ZERO(-1) : a is -0
n = BigDecimal::SIGN_POSITIVE_FINITE(2) : a is positive
n = BigDecimal::SIGN_NEGATIVE_FINITE(-2) : a is negative
n = BigDecimal::SIGN_POSITIVE_INFINITE(3) : a is +Infinity
n = BigDecimal::SIGN_NEGATIVE_INFINITE(-3) : a is -Infinity
The value in () is the actual value,see (Internal structure.
a.nan? returns True when a is NaN.
a.infinite? returns 1 when a is +,-1 when a is -, nil otherwise.
a.finite? returns true when a is neither nor NaN.
c = a.zero?
returns true if a is equal to 0,otherwise returns false
c = a.nonzero?
returns nil if a is 0,otherwise returns a itself.
decomposes a BigDecimal value to 4 parts. All 4 parts are returned as an array.
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")
f,x,y,z = a.split
where f=+1,x="314159265",y=10 and z=1
therefore,you can translate BigDecimal value to Float as:
s = "0."+x
b = f*(s.to_f)*(y**z)
is used for debugging output.
p a=BigDecimal::new("3.14",10)
should produce output like "#<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.
c = a.sqrt(n)
computes square root value of a with significant digit number n at least.
c = a ** n
returns the value of a powered by n. n must be an integer.
The same as ** method.
c = a.power(n)
returns the value of a powered by n(c=a**n). n must be an integer.
See,corresponding methods in Float class.
c = a <=> b
returns 0 if a==b,1 if a > b,and returns -1 if a < b.
a = BigDecimal.E(20)
c = a * "0.123456789123456789123456789" # A String is changed to BigDecimal object.
is performed normally.
a = BigDecimal.E(20)
c = "0.123456789123456789123456789" * a # ERROR
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.
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
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;
The decimal value 1234.56784321 is represented as(BASE=10000):0.1234 5678 4321*(10000)**1where 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.
file = File::open(....,"r")
s = BigDecimal::new("0")
while line = file.gets
s = s + line
end
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.
BigDecimal("2").div(3,12) # 2.0/3.0 => 0.6666666666 67E0
BigDecimal("6.66666666666666").round(12) # => 0.6666666666 667E1
#!/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