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). To use them,just require util.rb as:
require "bigdecimal/util.rb"
String to BigDecimal conversion, BigDecimal to String conversion
(in "nnnnnn.mmmm" form not in "0.xxxxxEn" form) etc are defined.
For details,see the util.rb code.
"new" method creates a new BigDecimal object.
a=BigDecimal::new(s[,n]) or
a=BigDecimal(s[,n]) or
where:
s: Initial value 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.
mode method controls BigDecimal computation.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 previous value set.
nil is returned if any argument is wrong.
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::COMP_MODE,flag)where flag must be one of:nil is returned if any argument is illegal.
COMP_MODE_TRUNCATE truncate COMP_MODE_ROUNDUP roundup,default COMP_MODE_CEIL ceil COMP_MODE_FLOOR floor COMP_MODE_EVEN Banker's rounding
The digit location for rounding operation can not be specified by mode method, use truncate/roundup/ceil/floor mthods for each instance instead.
Limits the maximum digits that the newly created BigDecimal objects can hold never exceed n. Returns maximum value before set. Zero,the default value,means no upper limit.
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.
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.
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.
c,r = a.div(b,n)
c,r = a.div(b,n) performs c = a / b, r is the residue of a / b. If necessary,the divide operation continues to n digits which c can hold. Unlike the divmod method,c is not always an integer. c is never rounded,and the equation a = c*b + r is always valid unless c is NaN or Infinity.
r = a%b
is the same as:
r = a-((a/b).floor)*b
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::new("1.23456").floor(4) # ==> 1.2345 c = BigDecimal::new("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::new("1.23456").ceil(4) # ==> 1.2346 c = BigDecimal::new("15.23456").ceil(-1) # ==> 20.0
c = a.round
round 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.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).If the second optional argument b is given with the non-zero value(default is zero) then so called Banker's rounding is performed.c = BigDecimal::new("1.23456").round(4) # ==> 1.2346 c = BigDecimal::new("15.23456").round(-1) # ==> 20.0
Suppose the digit p is to be rounded,then:
If p<5 then p is truncated
If p>5 then p is rounded up
If p is 5 then round up operation is taken only when the left hand side digit of p is odd.c = BigDecimal::new("1.23456").round(3,1) # ==> 1.234 c = BigDecimal::new("1.23356").round(3,1) # ==> 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,r = a.divmod(b) # a = c*b + r
returns the quotient and remainder of a/b.
a = c * b + r is always satisfied.
where c is the integer satisfying c = (a/b).floor
and,therefore r = a - c*b
r=a.remainder(b)
returns the remainder of a/b.
where c is the integer satisfying c = (a/b).fix
and,therefore: r = a - c*b
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(results look like "0.xxxxxEn").
s = a.to_s
If n is given,then a space is inserted after every n digits for readability.
s = a.to_s(n)
returns an integer holding exponent value of a.
n = a.exponent
means a = 0.xxxxxxx*10**n.
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.
c = a <=> b
returns 0 if a==b,1 if a > b,and returns -1 if a < b.
e = BigDecimal::E(n)
where e(=2.718281828....) is the base value of natural logarithm.
n specifies the length of significant digits of e.
e = BigDecimal::PI(n)
returns at least n digits of the ratio of the circumference of a circle to its diameter (pi=3.14159265358979....) using J.Machin's formula.
computes and returns sine and cosine value of a with significant digit number n at least.
sin,cos = a.sincos(n)
Computation may return bad results unless |a|<2*3.1415.....
c = a.exp(n)
computes the base of natural logarithm value(e=2.718281828....) powered by a with significant digit number n at least.
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.
#!/usr/local/bin/ruby
#
# pi.rb
# USAGE: ruby pi.rb n
# where n is the number of digits required.
# EX.: ruby pi.rb 1000
#
require "bigdecimal"
#
# Calculates 3.1415.... 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.exponent >= exp)
t = t*m25
u,r = 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.exponent >= exp )
t,r = t.div(m57121,sig)
u,r = t.div(k,sig)
pi = pi + u
k = k+two
end
pi
end
if $0 == __FILE__
print "PI("+ARGV[0]+"):\n"
p pi(ARGV[0].to_i)
end