role Rational
Number stored as numerator and denominator
[::NuT, ::DeT] does Real
Rational
is the common role for numbers that are stored as pairs of numerator and denominator. It is parameterized by the types of the numerator (NuT
) and denominator (DeT
). By default, these are Int
, but other types of Rational
are possible by using a different parameterization. In addition, Rational
objects are immutable throughout their life.
does Rational[UInt] ;my Positive = Positive.new(1,3);say ; # OUTPUT: «0.333333»my Positive =Positive.new(-2,3); # OUTPUT: «Type check failed in binding to parameter 'nu'; expected UInt but got Int (-2)»
Please note that, since DeT
is by default equal to NuT
, in this case both are instantiated to UInt
. Built into Perl 6 are Rat and FatRat, which both do the Rational
role.
Methods
method new
method new(NuT , DeT --> Rational)
Creates a new rational object from numerator and denominator, which it normalizes to the lowest terms. The $denominator
can be zero, in which case the numerator is normalized to -1
, 0
, or 1
depending on whether the original is negative, zero, or positive, respectively.
method Bool
Defined as:
multi method Bool(Rational: --> Bool)
Returns False
if numerator is 0
, otherwise returns True
. This applies for <0/0>
zero-denominator Rational as well, despite ?<0/0>.Num
being True
.
method Int
Defined as:
method Int(Rational: --> Int)
Coerces the invocant to Int by truncating non-whole portion of the represented number, if any. If the denominator is zero, will fail with X::Numeric::DivideByZero
.
method Num
Defined as:
method Num(Rational: --> Num)
Coerces the invocant to Num by dividing numerator by denominator. If denominator is 0
, returns Inf
, -Inf
, or NaN
, based on whether numerator is a positive number, negative number, or 0
, respectively.
method ceiling
Defined as:
method ceiling(Rational: --> Int)
Return the smallest integer not less than the invocant. If denominator is zero, fails with X::Numeric::DivideByZero
.
method floor
Defined as:
method floor(Rational: --> Int)
Return the largest integer not greater than the invocant. If denominator is zero, fails with X::Numeric::DivideByZero
.
method isNaN
method isNaN(Rational: --> Bool)
Tests whether the invocant's Num value is a NaN, an acronym for Not available Number. That is both its numerator and denominator are zero.
method numerator
method numerator(Rational: --> NuT)
Returns the numerator.
method denominator
method denominator(Rational: --> DeT)
Returns the denominator.
method nude
method nude(Rational: --> Positional)
Returns a list of the numerator and denominator.
method norm
method norm(Rational: --> Rational)
DEPRECATED as of 6.d. The method is no longer needed, because as of 6.d language version, it's required for Rational
type to be normalized on creation.
Returns a normalized Rational object, i.e. with positive denominator, and numerator and denominator coprime. The denominator can also by zero, but using it in any operation or a conversion to string will result in an exception.
use v6.c;my Rational = 3/0;say .norm.perl; # OUTPUT: «<1/0>»
say ; # OUTPUT: «Attempt to divide by zero when coercing Rational to Str
method base-repeating
method base-repeating(Rational: Int() = 10)
Returns a list of two strings that, when concatenated, represent the number in base $base
. The second element is the one that repeats. For example:
my (, ) = (19/3).base-repeating(10);say ; # OUTPUT: «6.»say ; # OUTPUT: «3»printf '%s(%s)', , ; # OUTPUT: «6.(3)»
19/3 is 6.333333... with the 3 repeating indefinitely.
If no repetition occurs, the second string is empty:
say (5/2).base-repeating(10).perl; # OUTPUT: «("2.5", "")»
The precision for determining the repeating group is limited to 1000 characters, above that, the second string is ???
.
$base
defaults to 10
.
method Range
Returns a Range object that represents the range of values supported.
Type Graph
Routines supplied by role Real
Rational does role Real, which provides the following routines:
(Real) method Bridge
Defined as:
method Bridge(Real:)
Default implementation coerces the invocant to Num and that's the behavior of this method in core Real types. This method primarily exist to make it easy to implement custom Real types by users, with the Bridge
method returning one of the core Real
types (NOT necessarily a Num) that best represent the custom Real
type. In turn, this lets all the core operators and methods obtain a usable value they can work with.
As an example, we can implement a custom Temperature
type. It has a unit of measure and the value, which are given during instantiation. We can implement custom operators or conversion methods that work with this type. When it comes to regular mathematical operators, however, we can simply use the .Bridge
method to convert the Temperature
to Kelvin expressed in one of the core numeric types:
is Realsub postfix:<℃>sub postfix:<℉>sub postfix:<K>my := 36.6℃;my := 451℉;my := 5778K;say ; # OUTPUT: «36.6 degrees C»say + + ; # OUTPUT: «6593.677777777778»say 123K + 456K; # OUTPUT: «579»
As we can see from the last two lines of the output, the type of the bridged result is not forced to be any particular core type. It is a Rat, when we instantiated Temperature
with a Rat
or when conversion was involved, and it is an Int when we instantiated Temperature
with an Int.
(Real) method Complex
method Complex(Real: --> Complex)
Converts the number to a Complex
with the number converted to a Num
as its real part and 0e0 as the imaginary part.
(Real) method Rat
method Rat(Real: Real = 1e-6)
Converts the number to a Rat
with the precision $epsilon
.
(Real) method Real
Defined as:
multi method Real(Real: --> Real)multi method Real(Real: --> Real)
The :D
variant simply returns the invocant. The :U
variant issues a warning about using an uninitialized value in numeric context and then returns self.new
.
(Real) routine rand
sub term:<rand> (--> Num)method rand(Real: --> Real)
Returns a pseudo-random number between zero (inclusive) and the number (non-inclusive). The Bridge
method is used to coerce the Real
to a numeric that supports rand method.
The term form returns a pseudo-random Num
between 0e0 (inclusive) and 1e0 (non-inclusive.)
(Real) method sign
method sign(Real:)
Returns -1
if the number is negative, 0
if it is zero and 1
otherwise.
(Real) method round
method round(Real: = 1)
Rounds the number to scale $scale
. If $scale
is 1, rounds to an integer. If scale is 0.1
, rounds to one digit after the comma etc.
(Real) method floor
method floor(Real --> Int)
Return the largest integer not greater than the number.
(Real) method ceiling
method ceiling(Real --> Int)
Returns the smallest integer not less than the number.
(Real) method truncate
method truncate(Real --> Int)
Rounds the number towards zero.
(Real) method polymod
method polymod(Real: +)
Returns the remainders after applying sequentially all divisors in the @mods
argument; the last element of the array will be the last remainder.
say (1e8+1).polymod(10 xx 8); # OUTPUT: «(1 0 0 0 0 0 0 0 1)»
10 xx 8
is simply an array with eight number 10s; the first division by 10 will return 1
as a remainder, while the rest, up to the last, will return 0. With 8 divisors, as above, the result will have one more elements, in this case for the last remainder.
(Real) method base
method base(Real: Int where 2..36, ? --> Str)
Converts the number to a string, using $base
as base. For $base
larger than ten, capital Latin letters are used.
255.base(16); # 'FF'
The optional $digits
argument asks for that many digits of fraction (which may not be negative). If omitted, a reasonable default is chosen based on type. For Int this default is 0. For Num, the default is 8. For Rational, the number of places is scaled to the size of the denominator, with a minimum of 6.
A special value of Whatever
(*
) can be given as $digits
, which functions the same as when $digits
is not specified for all Real
types except the Rationals
. For Rationals
, the Whatever
indicates that you wish all of the possible digits of the fractional part, but use caution: since there's no detection of repeating fractional parts (the algorithm will eventually stop after generating 2**63 digits).
The final digit produced is always rounded.
say pi.base(10, 3); # OUTPUT: «3.142»say (1/128).base(10, *); # OUTPUT: «0.0078125»say (1/100).base(10, *); # OUTPUT: «0.01»say (1/3) .base(10, *); # WRONG: endlessly repeating fractional part
For reverse operation, see parse-base
Routines supplied by role Numeric
Rational does role Numeric, which provides the following routines:
(Numeric) method Numeric
Defined as:
multi method Numeric(Numeric: --> Numeric)multi method Numeric(Numeric: --> Numeric)
The :D
variant simply returns the invocant. The :U
variant issues a warning about using an uninitialized value in numeric context and then returns self.new
.
(Numeric) method Int
method Int(Numeric: --> Int)
If this Numeric
is equivalent to a Real
, return the equivalent of calling truncate
on that Real
to get an Int
. Fail with X::Numeric::Real
otherwise.
(Numeric) method Rat
method Rat(Numeric: Real = 1.0e-6 --> Rat)
If this Numeric
is equivalent to a Real
, return a Rat
which is within $epsilon
of that Real
's value. Fail with X::Numeric::Real
otherwise.
(Numeric) method Num
method Num(Numeric: --> Num)
If this Numeric
is equivalent to a Real
, return that Real
as a Num
as accurately as is possible. Fail with X::Numeric::Real
otherwise.
(Numeric) method narrow
method narrow(Numeric --> Numeric)
Returns the number converted to the narrowest type that can hold it without loss of precision.
say (4.0 + 0i).narrow.perl; # OUTPUT: «4»say (4.0 + 0i).narrow.^name; # OUTPUT: «Int»
(Numeric) method ACCEPTS
multi method ACCEPTS(Numeric: )
Returns True
if $other
can be coerced to Numeric and is numerically equal to the invocant (or both evaluate to NaN
).
(Numeric) routine log
multi sub log(Numeric, Numeric = e --> Numeric)multi method log(Numeric: Numeric = e --> Numeric)
Calculates the logarithm to base $base
. Defaults to the natural logarithm. Returns NaN
if $base
is negative. Throws an exception if $base
is 1
.
(Numeric) routine log10
multi sub log10(Numeric --> Numeric)multi method log10(Numeric: --> Numeric)
Calculates the logarithm to base 10. Returns NaN
for negative arguments and -Inf
for 0
.
(Numeric) routine exp
multi sub exp(Numeric, Numeric = e --> Numeric)multi method exp(Numeric: Numeric = e --> Numeric)
Returns $base
to the power of the number, or e
to the power of the number if called without a second argument.
(Numeric) method roots
multi method roots(Numeric: Int --> Positional)
Returns a list of the $n
complex roots, which evaluate to the original number when raised to the $n
th power.
(Numeric) routine abs
multi sub abs(Numeric --> Real)multi method abs(Numeric: --> Real)
Returns the absolute value of the number.
(Numeric) routine sqrt
multi sub sqrt(Numeric --> Numeric)multi method sqrt(Numeric --> Numeric)
Returns a square root of the number. For real numbers the positive square root is returned.
On negative real numbers, sqrt
returns NaN
rather than a complex number, in order to not confuse people who are not familiar with complex arithmetic. If you want to calculate complex square roots, coerce to Complex
first, or use the roots
method.
(Numeric) method conj
multi method conj(Numeric --> Numeric)
Returns the complex conjugate of the number. Returns the number itself for real numbers.
(Numeric) method Bool
multi method Bool(Numeric:)
Returns False
if the number is equivalent to zero, and True
otherwise.
(Numeric) method succ
method succ(Numeric:)
Returns the number incremented by one (successor).
(Numeric) method pred
method pred(Numeric:)
Returns the number decremented by one (predecessor).