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

rat == object â true or false Instance Public methods Returns true if rat

2015-05-01 03:42:51
*

rat * numeric â numeric Instance Public methods Performs multiplication.

2015-05-01 03:14:31
rationalize

rat.rationalize â selfrat.rationalize(eps) â rational Instance Public methods

2015-05-01 04:14:17
to_i

rat.to_i â integer Instance Public methods Returns the truncated value as

2015-05-01 04:31:48
quo

rat.quo(numeric) â numeric Instance Public methods Performs division.

2015-05-01 04:12:23
floor

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

2015-05-01 04:00:27
-

rat - numeric â numeric Instance Public methods Performs subtraction.

2015-05-01 03:26:53
as_json

as_json(*) Instance Public methods

2015-05-01 03:44:16
to_d

r.to_d(precision) â bigdecimal Instance Public methods Converts a

2015-05-01 04:24:24
numerator

rat.numerator â integer Instance Public methods Returns the numerator.

2015-05-01 04:07:20