DRAFT: Synopsis 32: Setting Library - Numeric
Rod Adams <rod@rodadams.net>
Larry Wall <larry@wall.org>
Aaron Sherman <ajs@ajs.com>
Mark Stosberg <mark@summersault.com>
Carl Mäsak <cmasak@gmail.com>
Moritz Lenz <moritz@faui2k3.org>
Tim Nelson <wayland@wayland.id.au>
Stefan O'Rear <stefanor@cox.net>
Created: 19 Mar 2009 extracted from S29-functions.pod
Last Modified: 20 Sept 2012
Version: 16
The document is a draft.
If you read the HTML version, it is generated from the Pod in the specs repository under https://github.com/perl6/specs/blob/master/S32-setting-library/Numeric.pod so edit it there in the git repository if you would like to make changes.
This documents Bit, Int, Numeric, Rat, Complex, and Bool.
XXX So where are Bit, Int, and Rat
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 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;
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 $nth (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.
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(Cool $base as Int)
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.
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 --> Int ) is export
Returns the nearest integer to $x. 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.
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: --> Seq ) 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.
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.
class Rat does Real;
An immutable rational number, represented by two Ints, 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( --> Parcel[Int] )
Returns a Parcel 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.
Please post errors and feedback to perl6-language. If you are making a general laundry list, please separate messages by topic.
[ Top ] [ Index of Synopses ]