struct BigRational

Overview

Rational numbers are represented as the quotient of arbitrarily large numerators and denominators. Rationals are canonicalized such that the denominator and the numerator have no common factors, and that the denominator is positive. Zero has the unique representation 0/1.

require "big_rational"

r = BigRational.new(BigInt.new(7), BigInt.new(3))
r.to_s # => "7/3"

r = BigRational.new(3, -9)
r.to_s # => "-1/3"

It is implemented under the hood with GMP.

Defined in:

big/big_rational.cr

Instance Method Summary

, , , , ,

, , , , ,

, , , , ,

Instance methods inherited from struct Number

, , , , , , , , , , , , , , , , , ,

, , , , ,

, , , , ,

,

Instance methods inherited from class Object

, , , , , , , , , , , , , , , , , ,

,

Class Method Detail

def self.new(numerator : Int, denominator : Int) #

Create a new BigRational.

If denominator is 0, this will raise an exception.

def self.new(num : Int) #

Creates a new BigRational with num as the numerator and 1 for denominator.

Instance Method Detail

def *(other : BigRational) #

def *(other : Int) #

def +(other : BigRational) #

def +(other : Int) #

def -(other : BigRational) #

def -(other : Int) #

def - #

def /(other : Int) #

def /(other : BigRational) #

def <<(other : Int) #

Multiplies the rational by (2 ** other)

BigRational.new(2, 3) << 2 # => 8/3

def <=>(other : BigRational) #

def <=>(other : Float) #

def <=>(other : Int) #

def >>(other : Int) #

Divides the rational by (2 ** other)

BigRational.new(2, 3) >> 2 # => 1/6

def abs #

def clone #

def denominator #

def hash #

def inspect #

def inspect(io) #

def inv #

Returns a new BigRational as 1/r.

This will raise an exception if rational is 0.

def numerator #

def to_f #

Returns the Float64 representing this rational.

def to_f32 #

def to_f64 #

def to_s(io : IO, base = 10) #

def to_s(base = 10) #

Returns the string representing this rational.

Optionally takes a radix base (2 through 36).

r = BigRational.new(8243243, 562828882)
r.to_s     # => "8243243/562828882"
r.to_s(16) # => "7dc82b/218c1652"
r.to_s(36) # => "4woiz/9b3djm"

def to_unsafe #