DRAFT: Synopsis 32: Setting Library - Numeric
Created: 19 Mar 2009 extracted from S29-functions.pod
Last Modified: 14 Feb 2015 Version: 20
This documents Int, Numeric, Rat, Complex, and Bool.
multi method succ ( Bool $b: --> Bool ) is export
Returns Bool::True
.
multi method pred ( Bool $b: --> Bool ) is export
Returns Bool::False
.
Numeric
is a role for everything that's a scalar number. So Num
, Int
, Rat
, Complex
and other numeric types do that role. However it is an abstract interface, so $number.WHAT
will never return Numeric
.
Users who provide their own scalar numeric types are encouraged to implement the Numeric
role. It is intended that such types support the basic arithmetic operators to the extent possible, as well as ==
. In addition, it is hoped that comparison operators will at least return consistent results, even if there is no sensible mathematical ordering of your type. That allows functions like sort to not choke and die if they are handed a value of your type. (See also the Real
role for scalar numeric types that represent real numbers.)
The following are all defined in the Numeric
role:
Numeric
provides some constants in addition to the basic mathematical functions.
constant tau is export = 6.28318_53071_79586_47692_52867_66559_00576; constant pi is export = 3.14159_26535_89793_23846_26433_83279_50288; constant e is export = 2.71828_18284_59045_23536_02874_71352_66249; constant i is export = 1i;
τ
and π
are provided as aliases for tau
and pi
, respectively.
multi method Real ( --> Real )
If this Numeric
is equivalent to a Real
, return that Real
. (For instance, if this number is a Complex
with a zero imaginary part.) Fail with X::Numeric::Real
otherwise.
multi method Int ( --> 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.
multi method Rat ( Real $epsilon = 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.
multi method Num ( --> 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.
multi method succ ( Numeric $x: --> Numeric ) is export multi method succ ( Int $x: --> Int ) is export
Returns the successor of $x
. This method is used by prefix:<++>
and postfix:<++>
to increment the value in a container.
multi method pred ( Numeric $x: --> Numeric ) is export multi method pred ( Int $x: --> Int ) is export
Returns the predecessor of $x
. This method is used by prefix:<-->
and postfix:<-->
to decrement the value in a container.
multi method abs ( Numeric $x: --> Numeric ) is export
Absolute Value.
multi method conj ( Numeric $x: --> Numeric ) is export
The complex conjugate of the value. For non-complex types, returns self.
multi method exp ( Numeric $exponent: Numeric :$base = Num::e --> Numeric ) is export
Performs similar to $base ** $exponent
. $base
defaults to the constant e.
multi method log ( Numeric $x: Numeric $base = Num::e --> Numeric ) is export
Logarithm of base $base
, default Natural. Calling with $x == 0
is an error.
multi method log10 (Numeric $x: --> Numeric ) is export
A base 10
logarithm, otherwise identical to log
.
sub term:<rand> ( --> Num )
Pseudo random number in range 0 ..^ 1
. That is, 0
is theoretically possible, while 1
is not. Note that there is no unary rand
function in Perl 6, but there is a rand
method. For picking a random integer you probably want to use something like (1..6).pick
instead.
multi method sqrt ( Numeric $x: --> Numeric ) is export
Returns the principal square root of the parameter.
method roots (Numeric $x: Int $n ) is export
Returns a list of all $n
th (complex) roots of $x
. Returns NaN
if $n <= 0
, itself if $n == 0
, and is free to return a single NaN
if $x
is NaN
or Inf
, or in case of complex numbers if one of the components is.
multi postfix:<i> ( Numeric $x --> Complex )
Returns a complex number representing the parameter multiplied by the imaginary unit i
. Note that there is no .i
method. To follow a variable name with the postfix, it's necessary to use a backslash or parentheses:
$land\i ($land)i
multi method to-radians ( Numeric $x: TrigBase $base --> Numeric ) is export
Convert from $base
to radians.
multi method from-radians ( Numeric $x: TrigBase $base --> Numeric ) is export
Convert from radians to $base
.
multi method narrow ( Numeric $x: ) is export
Attempts to coerce the number to the narrowest type that can represent it accurately; for instance, a Rat
with a denominator of 1 maybe be coerced to an Int
instead; an integral Num
may likewise turn into an Int
. (Neither Num
nor Rat
convert to each other, however.) Complex
with a 0 imaginary part may narrow to a Real
type. Conjecturally, wide native types could narrow to narrower native types.
role Real does Numeric;
Real
, like Numeric
, is an abstract role that represents the interface of a real scalar number (i.e. neither Complex
nor vector-like). For example Num
, Int
, Bool
and Rat
implement the Real
role.
Users who provide their own scalar real numeric types are encouraged to implement the Real
role. Because real numbers are strictly-totally-ordered and Real
types try to emulate that property, it is desirable that any two Real
types be mutually compatible, even if they are not aware of each other. The current proposal requires you to define a Bridge
method in your Real
type, which converts your type into a neutral Real
type by restating it in terms of the fundamental Perl 6 types and calling Bridge
on them. This then makes the default Real
methods and operators all work with your Real
type. While the name of this method may changed, it is hoped that something like this will remain in the spec.
multi method Complex ( --> Complex )
Returns a Complex
whose real part is this Real
and whose imaginary part is 0.
multi method Str ( --> Str )
Returns the Real
as a Str
. All built-in Real
types format it as a decimal number, so for example, the Rat
5/4
is returned as "1.2"
.
multi method base($base, $digits?)
Returns a Str
representing the invocant in base $base
. Fails if $base
is smaller than 2
or larger than 36
.
For bases above ten, the digit repertoire is enhanced with uppercase latin characters starting from A
.
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 Rat, the number of places is scaled to the size of the denominator, with a minimum of 6.
The final digit produced is always rounded.
multi method floor ( Real $x: --> Int ) is export
Returns the highest integer not greater than $x
.
multi method ceiling ( Real $x: --> Int ) is export
Returns the lowest integer not less than $x
.
multi method round ( Real $x: $scale = 1 --> Real ) is export
With no arguments, returns the nearest integer to $x
. If $scale
is given, rounds $x to the nearest multiple of $scale
. The algorithm is:
floor($x / $scale + 0.5) * $scale
(Other rounding algorithms will be given extended names beginning with "round".)
multi method truncate ( Real $x: --> Int ) is export
Returns the closest integer to $x
whose absolute value is not greater than the absolute value of $x
. (In other words, just chuck any fractional part.) This is the default rounding function used by implicit integer conversions.
You may also truncate using explicit integer casts, either Int()
for an arbitrarily large integers, or int()
for native integers.
multi method sign ( Real $x: --> Int ) is export
Returns 1 when $x
is greater than 0, -1 when it is less than 0, 0 when it is equal to 0, or undefined when the value passed is undefined.
multi srand ( Real $seed = default_seed_algorithm())
Seed the generator rand
uses. $seed
defaults to some combination of various platform dependent characteristics to yield a non-deterministic seed. Note that you get one srand()
for free when you start a Perl program, so you must call srand()
yourself if you wish to specify a deterministic seed (or if you wish to be differently nondeterministic).
multi method rand (Real $x: --> Num ) is export
Pseudo random number in range 0 ..^ $x
. That is, 0
is theoretically possible, while $x
is not. For picking a random integer you probably want to use something like (1..6).pick
instead.
multi method cis (Real $angle: --> Complex ) is export
Returns 1.unpolar($angle)
multi method unpolar (Real $mag: Real $angle --> Complex ) is export
Returns a complex number specified in polar coordinates. Angle is in radians.
method polymod(*@mods)
Returns a sequence of mod results corresponding to the divisors in @mods
. If the number of divisors is finite, returns one more result than the number of divisors, and the final result is the remainder after all the divisions. If the number of divisors is infinite, runs until the remainder is 0. The Int
version of this method assumes all the divisors are also integers. Coerce the invocant to Num
or Rat
if you wish to use fractional operations.
class Num does Real
Num
is a machine-precision numeric real value.
Complex
is an immutable type. Each Complex
object stores two numbers, the real and imaginary part. For all practical purposes a Complex
with a NaN
in real or imaginary part may be considered a NaN
itself (and (NaN+1i) ~~ NaN
is True
).
Coercion of a Complex
to any Real
returns the real part (coerced, if necessary) if the imaginary part is 0, and fails otherwise. Comparison between a Real
number and a Complex
must be smart enough not to coerce the Complex
to a real number blindly.
multi method new(Real $re, Real $im --> Complex )
Constructs a Complex
number from real and imaginary part. This is the method form of $re+$im\i
. (But use the <1+2i>
form for literals, so that you don't have to worry about precedence or rely on constant folding.)
multi method polar (Complex $nim: --> List ) is export
Returns (magnitude, angle) corresponding to the complex number. The magnitude is non-negative, and the angle in the range -π ..^ π
.
multi method re( --> Real )
Returns the real part of the complex number.
multi method im( --> Real )
Returns the imaginary part of a complex number.
multi method conj(Complex $c --> Complex )
Returns ($c.re - $c.im\i)
, the complex conjugate.
multi method gist( --> Str )
Returns a string representation of the form "1+2i
", without internal spaces. (Str
coercion also returns this.)
multi method perl( --> Str )
Returns a string representation corresponding to the unambiguous val()
-based representation of complex literals, of the form "<1+2i>
", without internal spaces, and including the angles that keep the +
from being treated as a normal addition operator.
multi method floor ( Complex $c: --> Complex ) is export
Returns $c.re.floor + $c.im.floor
. That is, each of the real and imaginary parts is rounded to the highest integer not greater that the value of that part.
multi method ceiling ( Complex $c: --> Complex ) is export
Returns $c.re.ceiling + $c.im.ceiling
. That is, each of the real and imaginary parts is rounded to the lowest integer not less that the value of that part.
multi method round ( Complex $c: $scale = 1 --> Complex ) is export
With no arguments, rounds both the real and imaginary parts to the nearest integer and returns a new Complex number. If $scale
is given, rounds both parts of $c to the nearest multiple of $scale
. Uses the same algorithm as Real.round on each part of the number.
multi method truncate ( Complex $c: --> Complex ) is export
Removes the fractional part of both the real and imaginary parts of the number, using Real.truncate, and returns the result as a new Complex.
The following are also defined in Numeric
. Most trig functions are specified to operate in terms of radians, as the mathematical and programming standard. Functions are provided to convert other angle specifications to and from radians. Angle specifications are given in terms of enum TrigBase:
enum TrigBase is export ( Radians => 1, Degrees => (pi / 180), Gradians => (pi / 200), Circles => 2*pi );
Numeric multi method func ( Numeric $x ) is export
where func is one of: sin, cos, tan, asin, acos, atan, sec, cosec, cotan, asec, acosec, acotan, sinh, cosh, tanh, asinh, acosh, atanh, sech, cosech, cotanh, asech, acosech, acotanh.
Performs the various trigonometric functions. The argument is always expressed in radians. The return value from CORE::
versions of these functions is always Num
, unless domain limits force it to be Complex
instead.
If you prefer to express angles in units other than radians, you have two choices. First, you can convert the angles into radians, by multiplication:
sin(90 * Degrees)
or by using the to-radians
method:
sin(90.to-radians(Degrees));
Alternatively, you can use the trigbase
pragma to install a new set of trigonometric functions into the current lexical scope, which will handle a different unit:
use trigbase Degrees; sin(90)
The parameter to the trigbase pragma must be something that is usable as a number. The above code fragment is more or less equivalent to:
constant $?TRIGBASE = Degrees; sub sin($x) { CORE::sin($x * Degrees) } # repeat for all the other trig operators sin(90)
Two points must be emphasized. First, trigbase
has no effect on the method forms of trig operators; .sin
always expects radians. Second, because it defines dozens of subs, it's probably a good idea to use trigbase
in the highest scope where it makes sense.
The $?TRIGBASE
constant is not used by the trig operators themselves. It exists only to allow modules to be trigbase
aware.
multi method atan2 ( Real $y: Real $x = 1, TrigBase $base = CALLER::<$?TRIGBASE> --> Real ) multi atan2 ( Real $y, Real $x = 1, TrigBase $base = CALLER::<$?TRIGBASE> --> Real )
This second form of atan
computes the arctangent of $y/$x
, and takes the quadrant into account. Otherwise behaves as other trigonometric functions.
An Int
is an immutable, integral number of arbitrary size.
multi method expmod ( Int $x: Int $y, Int $mod --> Int ) is export
Returns $x
raised to the $y
power within modulus $mod
.
multi method is-prime ( Int $x: Int $tries = 100) is export
Returns True if $x
is known to be a prime, or is likely to be a prime based on a probabalistic Miller-Rabin test. (The optional argument tells how many times to iterate the probabalistic test, if such is necessary.)
Returns False if $x
is known not to be a prime.
multi method lsb ( Int $x: ) is export
Returns the least significant bit position containing a 1 bit, counting bit positions from least significant to most significant. (In other words, it's the base 2 logarithm of number represented by that 1 bit.)
This function returns Nil
on a 0 value, since there are no bits set. Negative integers are treated as 2's complement, so always have a lowest bit set somewhere, if only the sign bit. Hence, a -32768 returns an lsb of 15 regardless of whether it's stored in an int16
or an Int
.
multi method msb ( Int $x: ) is export
Returns the most significant bit position containing a 1 bit, that is, the base 2 logarithm of the top 1 bit.
This function returns Nil
on a 0 value. For negative values, the function is dependent on the type. For native types, signed integers are treated as unsigned, so a negative number stored in int64
will always return 63. Negative integers stored in an Int
notionally have an infinite number of 1 bits on top, which is a problem. Instead of returning +Inf
, which is relatively useless, we return the position of the first of that infinite supply of sign bits. So msb(-1)
returns 0, msb(-2)
returns 1, and msb(-32768)
returns 15, just as if we'd converted it from int16
to uint16
and examined that for its top bit.
class Rat does Real
An immutable rational number, represented by two Int
s, a numerator and a denominator. All interface methods return values as if the numerator and denominator were stored in a normal form: both numerator and denominator are minimal in their magnitude, and the denominator is positive. So Rat.new(2, -4).denominator
return 2
, because the normal form is -1/2
.
(An implementation is allowed to be lazy about this internally when it determines that normalizing repeatedly is detrimental to performance, such as when adding a column of numbers that all have an internal denominator of 100.)
multi method new(Int $num, Int $denom)
Constructs a Rat
object from the numerator and denominator. Fails if $denom == 0
. You can use division to produce a Rat
through constant folding, but generally if you know the values in advance, you should use one of literal forms so that you don't have to rely on precedence. You may use the val()
-based <3/5>
form, or you can simply write decimal numbers with a decimal point, since 12.34
is essentially identical to <1234/100>
as a literal.
multi method nude( --> List )
Returns a List
of numerator and denominator.
multi method denominator( --> Int )
Returns the denominator.
multi method numerator( --> Int )
Returns the numerator.
multi method gist( --> Str )
Returns a string representation of the number in decimal. If the number can be represented exactly in decimal, it will be. In any case, the portion before the decimal point (the "integer" part) is guaranteed to be exact. The precision of the fractional part is defined to be one more digit than the size of the denominator after the integer part has been removed, but at least 6 digits for repeating fractions. The final digit of the fractional part is rounded.
Str
coercion is identical to gist
.
multi method perl( --> Str )
Returns a string representation corresponding to the unambiguous val()
-based representation of rational literals. If the number can be represented exactly in decimal, it will be. Otherwise uses the form "<3/5>
", without internal spaces, and including the angles that keep the /
from being treated as a normal division operator.
multi method base-repeating($base)
Returns two strings representing the invocant in base $base
. Fails if $base
is smaller than 2
or larger than 36
.
For bases above ten, the digit repertoire is enhanced with uppercase latin characters starting from A
.
The first returned string is the non-repeating part of the representation. The second is the repeating part. The precision is arbitrarily limited to 100000. Above that, the repeating group will return '???'. If there is no repeating group, the second returned string is ''
.
Rod Adams <[email protected]> Larry Wall <[email protected]> Aaron Sherman <[email protected]> Mark Stosberg <[email protected]> Carl Mäsak <[email protected]> Moritz Lenz <[email protected]> Tim Nelson <[email protected]> Stefan O'Rear <[email protected]>[ Top ] [ Index of Synopses ]