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)
truncate

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

2015-05-01 04:48:54
+

rat + numeric â numeric Instance Public methods Performs addition.

2015-05-01 03:20:32
**

**(other) Instance Public methods Exponentiate by other

2015-05-01 03:18:35
denominator

rat.denominator â integer Instance Public methods Returns the denominator

2015-05-01 03:53:35
to_s

rat.to_s â string Instance Public methods Returns the value as a string.

2015-05-01 04:42:45
to_f

rat.to_f â float Instance Public methods Return the value as a float.

2015-05-01 04:26:05
inspect

rat.inspect â string Instance Public methods Returns the value as a string

2015-05-01 04:04:42
/ 2

rat / numeric â numeric Instance Public methods Performs division.

2015-05-01 03:31:26
ceil

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

2015-05-01 03:51:28
to_json

to_json(*) Instance Public methods

2015-05-01 04:35:17