Type:
Class

When mathn is required Rational is changed to simplify the use of Rational operations.

Normal behaviour:

Rational.new!(1,3) ** 2 # => Rational(1, 9)
(1 / 3) ** 2            # => 0

require 'mathn' behaviour:

(1 / 3) ** 2            # => 1/9

A rational number can be represented as a paired integer number; a/b (b>0). Where a is numerator and b is denominator. Integer a equals rational a/1 mathematically.

In ruby, you can create rational object with Rational, #to_r or rationalize method. The return values will be irreducible.

Rational(1)      #=> (1/1)
Rational(2, 3)   #=> (2/3)
Rational(4, -6)  #=> (-2/3)
3.to_r           #=> (3/1)

You can also create rational object from floating-point numbers or strings.

Rational(0.3)    #=> (5404319552844595/18014398509481984)
Rational('0.3')  #=> (3/10)
Rational('2/3')  #=> (2/3)

0.3.to_r         #=> (5404319552844595/18014398509481984)
'0.3'.to_r       #=> (3/10)
'2/3'.to_r       #=> (2/3)
0.3.rationalize  #=> (3/10)

A rational object is an exact number, which helps you to write program without any rounding errors.

10.times.inject(0){|t,| t + 0.1}              #=> 0.9999999999999999
10.times.inject(0){|t,| t + Rational('0.1')}  #=> (1/1)

However, when an expression has inexact factor (numerical value or operation), will produce an inexact result.

Rational(10) / 3   #=> (10/3)
Rational(10) / 3.0 #=> 3.3333333333333335

Rational(-8) ** Rational(1, 3)
                   #=> (1.0000000000000002+1.7320508075688772i)
fdiv

rat.fdiv(numeric) â float Instance Public methods Performs division and returns

2015-05-01 03:57:44
round

rat.round â integerrat.round(precision=0) â rational Instance Public methods

2015-05-01 04:18:05
<=>

rational numeric â -1, 0, +1 or nil Instance Public methods Performs comparison

2015-05-01 03:35:25
json_create

json_create(object) Class Public methods

2015-05-01 03:13:08
to_r

rat.to_r â self Instance Public methods Returns self.

2015-05-01 04:37:27