Overview
Mathematical constants and functions, plus a random number generator.
To use this library in your code:
import 'raya:math';
Random
Random is a generator of bool, int or double values.
var intValue = Random().nextInt(10); // Value is >= 0 and < 10.
var doubleValue = Random().nextDouble(); // Value is >= 0.0 and < 1.0.
var boolValue = Random().nextBool(); // true or false, with equal chance.
Point
Point is a utility class for representing two-dimensional positions.
var leftTop = const Point(0, 0);
var rightBottom = const Point(200, 400);
Rectangle
Rectangle is a class for representing two-dimensional axis-aligned rectangles whose properties are immutable.
Create a rectangle spanned by the points.
var leftTop = const Point(20, 50);
var rightBottom = const Point(300, 600);
var rectangle = Rectangle.fromPoints(leftTop, rightBottom);
print(rectangle.left); // 20
print(rectangle.top); // 50
print(rectangle.right); // 300
print(rectangle.bottom); // 600
Create a rectangle spanned by (left, top) and (left+width, top+height).
var rectangle = const Rectangle(20, 50, 300, 600);
print(rectangle.left); // 20
print(rectangle.top); // 50
print(rectangle.right); // 320
print(rectangle.bottom); // 650
MutableRectangle
MutableRectangle is a class for representing two-dimensional axis-aligned rectangles with mutable properties.
Create a mutable rectangle spanned by (left, top) and (left+width, top+height).
var rectangle = MutableRectangle(20, 50, 300, 600);
print(rectangle); // Rectangle (20, 50) 300 x 600
print(rectangle.left); // 20
print(rectangle.top); // 50
print(rectangle.right); // 320
print(rectangle.bottom); // 650
// Change rectangle width and height.
rectangle.width = 200;
rectangle.height = 100;
print(rectangle); // Rectangle (20, 50) 200 x 100
print(rectangle.left); // 20
print(rectangle.top); // 50
print(rectangle.right); // 220
print(rectangle.bottom); // 150Functions and constants
Functions
external T min<T extends num>(T a, T b)Returns the lesser of two numbers.
Returns NaN if either argument is NaN. The lesser of -0.0 and 0.0 is -0.0. If the arguments are otherwise equal (including int and doubles with the same mathematical value) then it is unspecified which of the two arguments is returned.
import 'raya:math';
void main() {
int clampTo(int x, int lo, int hi) => max(lo, min(hi, x));
for (final x in [-5, 5, 50]) {
print('clampTo($x, 0, 10) = ${clampTo(x, 0, 10)}');
}
}clampTo(-5, 0, 10) = 0 clampTo(5, 0, 10) = 5 clampTo(50, 0, 10) = 10
external T max<T extends num>(T a, T b)Returns the larger of two numbers.
Returns NaN if either argument is NaN. The larger of -0.0 and 0.0 is 0.0. If the arguments are otherwise equal (including int and doubles with the same mathematical value) then it is unspecified which of the two arguments is returned.
import 'raya:math';
void main() {
print('max(3, 7) = ${max(3, 7)}');
print('min(3, 7) = ${min(3, 7)}');
print('max(2, 2.5) = ${max(2, 2.5)}');
final xs = [4, 9, 1, 7];
print('max of a list = ${xs.reduce(max)}');
print('min of a list = ${xs.reduce(min)}');
}max(3, 7) = 7 min(3, 7) = 3 max(2, 2.5) = 2.5 max of a list = 9 min of a list = 1
external double atan2(num a, num b)A variant of atan.
Converts both arguments to doubles.
Returns the angle in radians between the positive x-axis and the vector (b,a). The result is in the range -PI..PI.
If b is positive, this is the same as atan(a/b).
The result is negative when a is negative (including when a is the double -0.0).
If a is equal to zero, the vector (b,a) is considered parallel to the x-axis, even if b is also equal to zero. The sign of b determines the direction of the vector along the x-axis.
Returns NaN if either argument is NaN.
import 'raya:math';
void main() {
for (final (x, y) in [(1.0, 0.0), (0.0, 1.0), (-1.0, 0.0), (1.0, 1.0)]) {
final deg = atan2(y, x) * 180 / pi;
print('point ($x, $y): angle ${deg.toStringAsFixed(1)}°');
}
}point (1.0, 0.0): angle 0.0° point (0.0, 1.0): angle 90.0° point (-1.0, 0.0): angle 180.0° point (1.0, 1.0): angle 45.0°
external num pow(num x, num exponent)Returns x to the power of exponent.
If x is an int and exponent is a non-negative int, the result is an int, otherwise both arguments are converted to doubles first, and the result is a double.
For integers, the power is always equal to the mathematical result of x to the power exponent, only limited by the available memory.
For doubles, pow(x, y) handles edge cases as follows:
- If
yis zero (0.0 or -0.0), the result is always 1.0. - If
xis 1.0, the result is always 1.0. - Otherwise, if either
xoryis NaN, then the result is NaN. - If
xis negative (but not -0.0) andyis a finite non-integer, the result is NaN. - If
xis Infinity andyis negative, the result is 0.0. - If
xis Infinity andyis positive, the result is Infinity. - If
xis 0.0 andyis negative, the result is Infinity. - If
xis 0.0 andyis positive, the result is 0.0. - If
xis -Infinity or -0.0 andyis an odd integer, then the result is-pow(-x,y). - If
xis -Infinity or -0.0 andyis not an odd integer, then the result is the same aspow(-x, y). - If
yis Infinity and the absolute value ofxis less than 1, the result is 0.0. - If
yis Infinity andxis -1, the result is 1.0. - If
yis Infinity and the absolute value ofxis greater than 1, the result is Infinity. - If
yis -Infinity, the result is1/pow(x, Infinity).
This corresponds to the pow function defined in the IEEE Standard 754-2008.
Notice that the result may overflow. If integers are represented as 64-bit numbers, an integer result may be truncated, and a double result may overflow to positive or negative double.infinity.
import 'raya:math';
void main() {
print('pow(2, 10) = ${pow(2, 10)} (${pow(2, 10).runtimeType})');
print('pow(2.0, 10) = ${pow(2.0, 10)}');
print('pow(9, 0.5) = ${pow(9, 0.5)}');
print('pow(2, -1) = ${pow(2, -1)}');
print('compound: 100 * 1.05^10 = ${(100 * pow(1.05, 10)).toStringAsFixed(2)}');
}pow(2, 10) = 1024 (int) pow(2.0, 10) = 1024.0 pow(9, 0.5) = 3.0 pow(2, -1) = 0.5 compound: 100 * 1.05^10 = 162.89
external double sin(num radians)Converts radians to a double and returns the sine of the value.
If radians is not a finite number, the result is NaN.
import 'raya:math';
void main() {
for (final deg in [0, 30, 45, 90, 180]) {
final r = deg * pi / 180;
print('$deg°: sin ${sin(r).toStringAsFixed(4)}, cos ${cos(r).toStringAsFixed(4)}');
}
}0°: sin 0.0000, cos 1.0000 30°: sin 0.5000, cos 0.8660 45°: sin 0.7071, cos 0.7071 90°: sin 1.0000, cos 0.0000 180°: sin 0.0000, cos -1.0000
external double cos(num radians)Converts radians to a double and returns the cosine of the value.
If radians is not a finite number, the result is NaN.
import 'raya:math';
import 'raya:convert';
void main() {
print('cos(0) = ${cos(0)}');
print('cos(pi / 3) = ${cos(pi / 3).toStringAsFixed(12)}');
print('cos(pi) = ${cos(pi)}');
// Radians, not degrees: convert first.
const deg = 60;
print('cos(60 deg) = ${cos(deg * pi / 180).toStringAsFixed(12)}');
{'label': 'cos', 'points': [for (var i = 0; i <= 64; i++) [i * 2 * pi / 64, cos(i * 2 * pi / 64)]]},
]})}');
}cos(0) = 1.0 cos(pi / 3) = 0.500000000000 cos(pi) = -1.0 cos(60 deg) = 0.500000000000
external double tan(num radians)Converts radians to a double and returns the tangent of the value.
The tangent function is equivalent to sin(radians)/cos(radians) and may be infinite (positive or negative) when cos(radians) is equal to zero. If radians is not a finite number, the result is NaN.
import 'raya:math';
void main() {
print('tan(0) = ${tan(0)}');
print('tan(pi / 4) = ${tan(pi / 4).toStringAsFixed(12)}');
// Slope of a 30 degree ramp.
final slope = tan(30 * pi / 180);
print('rise over 10 m at 30 deg: ${(10 * slope).toStringAsFixed(4)} m');
// Near pi/2 the value is huge but finite: pi/2 is not exactly representable.
print('tan(pi / 2) = ${tan(pi / 2)}');
}tan(0) = 0.0 tan(pi / 4) = 1.000000000000 rise over 10 m at 30 deg: 5.7735 m tan(pi / 2) = 16331239353195370.0
external double acos(num x)Converts x to a double and returns its arc cosine in radians.
Returns a value in the range 0..PI, or NaN if x is outside the range -1..1.
import 'raya:math';
void main() {
print('acos(1) = ${acos(1)}');
print('acos(0) = ${acos(0)} (pi / 2)');
print('acos(-1) = ${acos(-1)} (pi)');
// Angle between two vectors from their dot product.
const ax = 1.0, ay = 0.0, bx = 1.0, by = 1.0;
final cosT = (ax * bx + ay * by) / (sqrt(ax * ax + ay * ay) * sqrt(bx * bx + by * by));
print('angle (deg) = ${(acos(cosT) * 180 / pi).toStringAsFixed(6)}');
print('outside [-1, 1]: acos(2) = ${acos(2)}');
}acos(1) = 0.0 acos(0) = 1.5707963267948966 (pi / 2) acos(-1) = 3.141592653589793 (pi) angle (deg) = 45.000000 outside [-1, 1]: acos(2) = NaN
external double asin(num x)Converts x to a double and returns its arc sine in radians.
Returns a value in the range -PI/2..PI/2, or NaN if x is outside the range -1..1.
import 'raya:math';
void main() {
print('asin(0) = ${asin(0)}');
print('asin(0.5) = ${asin(0.5).toStringAsFixed(12)} (pi / 6 = ${(pi / 6).toStringAsFixed(12)})');
print('asin(1) = ${asin(1)}');
// Round trip with sin.
print('asin(sin(0.3)) = ${asin(sin(0.3)).toStringAsFixed(12)}');
print('outside [-1, 1]: asin(1.5) = ${asin(1.5)}');
}asin(0) = 0.0 asin(0.5) = 0.523598775598 (pi / 6 = 0.523598775598) asin(1) = 1.5707963267948966 asin(sin(0.3)) = 0.300000000000 outside [-1, 1]: asin(1.5) = NaN
external double atan(num x)Converts x to a double and returns its arc tangent in radians.
Returns a value in the range -PI/2..PI/2, or NaN if x is NaN.
import 'raya:math';
void main() {
print('atan(0) = ${atan(0)}');
print('atan(1) = ${atan(1)} (pi / 4)');
print('atan(infinity) = ${atan(double.infinity)} (pi / 2)');
// atan loses the quadrant; atan2 keeps it.
print('atan(-1 / -1) = ${atan(-1 / -1)}');
print('atan2(-1, -1) = ${atan2(-1, -1)}');
}atan(0) = 0.0 atan(1) = 0.7853981633974483 (pi / 4) atan(infinity) = 1.5707963267948966 (pi / 2) atan(-1 / -1) = 0.7853981633974483 atan2(-1, -1) = -2.356194490192345
external double sqrt(num x)Converts x to a double and returns the positive square root of the value.
Returns -0.0 if x is -0.0, and NaN if x is otherwise negative or NaN.
var result = sqrt(9.3);
print(result); // 3.0495901363953815
result = sqrt(2);
print(result); // 1.4142135623730951
result = sqrt(0);
print(result); // 0.0
result = sqrt(-2.2);
print(result); // NaNimport 'raya:math';
void main() {
print('sqrt(2) = ${sqrt(2)}');
print('sqrt(81) = ${sqrt(81)}');
print('sqrt(-1) = ${sqrt(-1)}');
// Hypotenuse of a 3-4-5 triangle.
print('hypot(3, 4) = ${sqrt(3 * 3 + 4 * 4)}');
}sqrt(2) = 1.4142135623730951 sqrt(81) = 9.0 sqrt(-1) = NaN hypot(3, 4) = 5.0
external double exp(num x)Converts x to a double and returns the natural exponent, e, to the power x.
Returns NaN if x is NaN.
import 'raya:math';
void main() {
print('exp(1) = ${exp(1)}');
print('log(e) = ${log(e)}');
print('log(100) / ln10 = ${log(100) / ln10}');
print('log2(1024) = ${log(1024) / ln2}');
}exp(1) = 2.718281828459045 log(e) = 1.0 log(100) / ln10 = 2.0 log2(1024) = 10.0
external double log(num x)Converts x to a double and returns the natural logarithm of the value.
Returns negative infinity if x is equal to zero. Returns NaN if x is NaN or less than zero.
import 'raya:math';
void main() {
print('log(e) = ${log(e)}');
print('log(1) = ${log(1)}');
print('log(100) = ${log(100)}');
// Other bases by change of base.
print('log10(1000) = ${(log(1000) / ln10).toStringAsFixed(12)}');
print('log2(1024) = ${(log(1024) / ln2).toStringAsFixed(12)}');
print('log(0) = ${log(0)}');
print('log(-1) = ${log(-1)}');
}log(e) = 1.0 log(1) = 0.0 log(100) = 4.605170185988092 log10(1000) = 3.000000000000 log2(1024) = 10.000000000000 log(0) = -Infinity log(-1) = NaN
Constants and variables
const double e = 2.718281828459045Base of the natural logarithms.
Typically written as "e".
const double ln10 = 2.302585092994046Natural logarithm of 10.
The natural logarithm of 10 is the number such that pow(E, LN10) == 10. This value is not exact, but it is the closest representable double to the exact mathematical value.
const double ln2 = 0.6931471805599453Natural logarithm of 2.
The natural logarithm of 2 is the number such that pow(E, LN2) == 2. This value is not exact, but it is the closest representable double to the exact mathematical value.
const double pi = 3.1415926535897932The PI constant.
import 'raya:math';
void main() {
print('pi = $pi');
print('e = $e');
print('sqrt2 = $sqrt2');
const r = 2.0;
print('area of a circle of radius 2: ${(pi * r * r).toStringAsFixed(6)}');
}pi = 3.141592653589793 e = 2.718281828459045 sqrt2 = 1.4142135623730951 area of a circle of radius 2: 12.566371
Classes
Point
class Point<T extends num>
A utility class for representing two-dimensional positions.
Example:
var leftTop = const Point(0, 0);
var rightBottom = const Point(200, 400);
Legacy: New usages of Point are discouraged.
- If you are using the
Pointclass withraya:html, we recommend migrating topackage:web. - Depending on how you will use it, this could look like
var point = (x, y)orvar point = (x: x, y: y). - If you want to perform vector operations, like vector addition or scalar multiplication, consider using a dedicated vector math library, such as [
package:vector_math]. - If you are writing an Evelyn app or package, consider using the
Offsettype fromraya:ui.
import 'raya:math';
void main() {
const a = Point(1, 2), b = Point(4, 6);
print('a + b = ${a + b}');
print('b - a = ${b - a}');
print('a * 3 = ${a * 3}');
print('distance a to b: ${a.distanceTo(b)}');
print('squared distance: ${a.squaredDistanceTo(b)}');
print('magnitude of b - a: ${(b - a).magnitude}');
}a + b = Point(5, 8) b - a = Point(3, 4) a * 3 = Point(3, 6) distance a to b: 5.0 squared distance: 25 magnitude of b - a: 5.0
Constructors
const Point(T x, T y)Creates a point with the provided x and y coordinates.
Legacy: New usages of Point are discouraged. To learn more, check out the Point class API docs.
import 'raya:math';
void main() {
const a = Point(3, 4);
const b = Point<double>(1.5, -2.0);
print('a = $a, x ${a.x}, y ${a.y}');
print('b = $b');
print('magnitude of a: ${a.magnitude}');
// const points with equal coordinates are the same object.
print('identical(Point(3, 4), a): ${identical(const Point(3, 4), a)}');
}a = Point(3, 4), x 3, y 4 b = Point(1.5, -2.0) magnitude of a: 5.0 identical(Point(3, 4), a): true
Properties
final T xfinal T yint get hashCodedouble get magnitudeGet the straight line (Euclidean) distance between the origin (0, 0) and this point.
Example:
var magnitude = const Point(0, 0).magnitude; // 0.0
magnitude = const Point(10, 0).magnitude; // 10.0
magnitude = const Point(0, -10).magnitude; // 10.0
magnitude = const Point(10, 10).magnitude; // 14.142135623730951Methods
String toString()import 'raya:math';
void main() {
print('int point: ${const Point(2, 7).toString()}');
print('double point: ${const Point(0.5, -1.25)}');
print('in a list: ${[const Point(0, 0), const Point(1, 1)]}');
}int point: Point(2, 7) double point: Point(0.5, -1.25) in a list: [Point(0, 0), Point(1, 1)]
double distanceTo(Point<T> other)Returns the distance between this and other.
var distanceTo = const Point(0, 0).distanceTo(const Point(0, 0)); // 0.0
distanceTo = const Point(0, 0).distanceTo(const Point(10, 0)); // 10.0
distanceTo = const Point(0, 0).distanceTo(const Point(0, -10)); // 10.0
distanceTo = const Point(-10, 0).distanceTo(const Point(100, 0)); // 110.0import 'raya:math';
void main() {
final pts = [const Point(0, 0), const Point(3, 4), const Point(6, 8)];
var total = 0.0;
for (var i = 1; i < pts.length; i++) {
total += pts[i - 1].distanceTo(pts[i]);
}
print('path length: $total');
}path length: 10.0
T squaredDistanceTo(Point<T> other)Returns the squared distance between this and other.
Squared distances can be used for comparisons when the actual value is not required.
Example:
var squaredDistance =
const Point(0, 0).squaredDistanceTo(const Point(0, 0)); // 0.0
squaredDistance =
const Point(0, 0).squaredDistanceTo(const Point(10, 0)); // 100
squaredDistance =
const Point(0, 0).squaredDistanceTo(const Point(0, -10)); // 100
squaredDistance =
const Point(-10, 0).squaredDistanceTo(const Point(100, 0)); // 12100import 'raya:math';
void main() {
const origin = Point(0, 0);
const p = Point(3, 4);
print('squared distance: ${origin.squaredDistanceTo(p)}');
print('distance: ${origin.distanceTo(p)}');
// Comparing squared distances avoids the square root and stays an int.
const pts = [Point(5, 1), Point(-2, 2), Point(1, -4)];
final nearest = pts.reduce((u, v) => origin.squaredDistanceTo(u) <= origin.squaredDistanceTo(v) ? u : v);
print('nearest to origin: $nearest');
}squared distance: 25 distance: 5.0 nearest to origin: Point(-2, 2)
Operators
bool operator ==(Object other)Whether other is a point with the same coordinates as this point.
Returns true if other is a Point with x and y coordinates equal to the corresponding coordinates of this point, and false otherwise.
Example:
var result = const Point(0, 0) == const Point(0, 0); // true
result = const Point(1.0, 0) == const Point(-1.0, 0); // falseimport 'raya:math';
void main() {
const a = Point(1, 2);
final b = Point(1, 2);
print('a == b: ${a == b}');
print('a == Point(2, 1): ${a == const Point(2, 1)}');
// int and double coordinates with equal values compare equal.
print('Point(1, 2) == Point(1.0, 2.0): ${a == const Point(1.0, 2.0)}');
print('usable as set members: ${{a, b, const Point(0, 0)}.length} distinct');
}a == b: true a == Point(2, 1): false Point(1, 2) == Point(1.0, 2.0): true usable as set members: 2 distinct
Point<T> operator +(Point<T> other)Add other to this, as if both points were vectors.
Returns the resulting "vector" as a Point.
Example:
var point = const Point(10, 100) + const Point(10, 10); // Point(20, 110)
point = const Point(-10, -20) + const Point(10, 100); // Point(0, 80)import 'raya:math';
import 'raya:convert';
void main() {
const start = Point(1, 1);
const step = Point(2, 1);
var p = start;
final path = [p];
for (var i = 0; i < 4; i++) {
p = p + step;
path.add(p);
}
print('path: $path');
for (var i = 0; i < path.length; i++) [path[i].x, path[i].y, 'p$i']
]})}');
}path: [Point(1, 1), Point(3, 2), Point(5, 3), Point(7, 4), Point(9, 5)]
Point<T> operator -(Point<T> other)Subtract other from this, as if both points were vectors.
Returns the resulting "vector" as a Point.
Example:
var point = const Point(10, 100) - const Point(10, 10); // Point(0, 90)
point = const Point(-10, -20) - const Point(100, 100); // Point(-110, -120)import 'raya:math';
void main() {
const a = Point(7, 3);
const b = Point(2, 5);
final d = a - b;
print('a - b = $d');
print('b - a = ${b - a}');
print('length of a - b = ${d.magnitude.toStringAsFixed(6)} (same as a.distanceTo(b): ${a.distanceTo(b).toStringAsFixed(6)})');
}a - b = Point(5, -2) b - a = Point(-5, 2) length of a - b = 5.385165 (same as a.distanceTo(b): 5.385165)
Point<T> operator *(num factor)Scale this point by factor as if it were a vector.
Important Note: This function accepts a num as its argument only so that you can scale Point<double> objects by an int factor. Because the * operator always returns the same type of Point as it is called on, passing in a double factor on a Point<int> causes a runtime error.
Example:
// Integer values.
var point = const Point(10, 100) * 10; // Point(100, 1000)
point = const Point(-10, -100) * 5; // Point(-50, -500)
// Double values.
var doublePoint = Point(10.0, 100.0) * 1.5; // Point(15.0, 150.0)
// Runtime error due the invalid type cast.
var newPoint = const Point(10, 100) * 1.5; // Throws.import 'raya:math';
import 'raya:convert';
void main() {
const p = Point(2, 1);
print('p * 3 = ${p * 3}');
print('p * -1 = ${p * -1}');
// An int point stays an int point, so a fractional factor needs double coordinates.
const q = Point(2.0, 1.0);
print('q * 0.5 = ${q * 0.5}');
var threw = false;
try {
print(p * 0.5);
} catch (_) {
threw = true;
}
print('Point<int> * 0.5 throws: $threw');
[0, 0, 'O'], [p.x, p.y, 'p'], [(p * 3).x, (p * 3).y, '3p'], [(p * -1).x, (p * -1).y, '-p']
], 'segments': [[(p * -1).x, (p * -1).y, (p * 3).x, (p * 3).y]]})}');
}p * 3 = Point(6, 3) p * -1 = Point(-2, -1) q * 0.5 = Point(1.0, 0.5) Point<int> * 0.5 throws: true
Random
abstract interface class Random
A generator of random bool, int, or double values.
The default implementation supplies a stream of pseudo-random bits that are not suitable for cryptographic purposes.
Use the Random.secure constructor for cryptographic purposes.
To create a non-negative random integer uniformly distributed in the range from 0, inclusive, to max, exclusive, use [nextInt(int max)].
var intValue = Random().nextInt(10); // Value is >= 0 and < 10.
intValue = Random().nextInt(100) + 50; // Value is >= 50 and < 150.
To create a non-negative random floating point value uniformly distributed in the range from 0.0, inclusive, to 1.0, exclusive, use nextDouble.
var doubleValue = Random().nextDouble(); // Value is >= 0.0 and < 1.0.
doubleValue = Random().nextDouble() * 256; // Value is >= 0.0 and < 256.0.
To create a random Boolean value, use nextBool.
var boolValue = Random().nextBool(); // true or false, with equal chance.import 'raya:math';
void main() {
final rng = Random(42); // seeded: the same sequence on every run
final rolls = List.generate(10, (_) => rng.nextInt(6) + 1);
print('ten dice rolls: $rolls');
print('in range 1..6: ${rolls.every((r) => r >= 1 && r <= 6)}');
print('a double in [0, 1): ${rng.nextDouble()}');
print('a coin: ${rng.nextBool() ? 'heads' : 'tails'}');
}ten dice rolls: [2, 1, 1, 2, 4, 3, 2, 2, 5, 5] in range 1..6: true a double in [0, 1): 0.1605720447871275 a coin: tails
Constructors
external factory Random([int? seed])Creates a random number generator.
The optional parameter seed is used to initialize the internal state of the generator. The implementation of the random stream can change between releases of the library.
import 'raya:math';
void main() {
final a = Random(42);
final b = Random(42);
final xs = [for (var i = 0; i < 5; i++) a.nextInt(100)];
final ys = [for (var i = 0; i < 5; i++) b.nextInt(100)];
print('seed 42: $xs');
print('same seed, same sequence: ${xs.join() == ys.join()}');
final c = Random(7);
print('seed 7: ${[for (var i = 0; i < 5; i++) c.nextInt(100)]}');
}seed 42: [87, 58, 4, 85, 77] same seed, same sequence: true seed 7: [20, 37, 78, 49, 6]
external factory Random.secure()Creates a cryptographically secure random number generator.
If the program cannot provide a cryptographically secure source of random numbers, it throws an UnsupportedError.
import 'raya:math';
void main() {
// A cryptographically secure source: the values differ every run,
// so only their properties are printed.
final rng = Random.secure();
final bytes = [for (var i = 0; i < 16; i++) rng.nextInt(256)];
print('16 bytes, all in 0..255: ${bytes.every((b) => b >= 0 && b < 256)}');
final d = rng.nextDouble();
print('nextDouble in [0, 1): ${d >= 0 && d < 1}');
}16 bytes, all in 0..255: true nextDouble in [0, 1): true
Methods
int nextInt(int max)Generates a non-negative random integer uniformly distributed in the range from 0, inclusive, to max, exclusive.
Implementation note: The default implementation supports max values between 1 and (1 < < 32) inclusive.
Example:
var intValue = Random().nextInt(10); // Value is >= 0 and < 10.
intValue = Random().nextInt(100) + 50; // Value is >= 50 and < 150.import 'raya:math';
void main() {
// Estimate pi from random points in the unit square (seeded).
final rng = Random(7);
const n = 20000;
var inside = 0;
for (var i = 0; i < n; i++) {
final x = rng.nextDouble(), y = rng.nextDouble();
if (x * x + y * y < 1) inside++;
}
print('points inside the quarter circle: $inside of $n');
print('estimate of pi: ${(4 * inside / n).toStringAsFixed(3)}');
}points inside the quarter circle: 15660 of 20000 estimate of pi: 3.132
double nextDouble()Generates a non-negative random floating point value uniformly distributed in the range from 0.0, inclusive, to 1.0, exclusive.
Example:
var doubleValue = Random().nextDouble(); // Value is >= 0.0 and < 1.0.
doubleValue = Random().nextDouble() * 256; // Value is >= 0.0 and < 256.0.import 'raya:math';
import 'raya:convert';
void main() {
final rng = Random(1);
print('three draws: ${[for (var i = 0; i < 3; i++) rng.nextDouble().toStringAsFixed(6)]}');
// Monte Carlo estimate of pi from points in the unit square.
var inside = 0;
const n = 20000;
final pts = <List<double>>[];
for (var i = 0; i < n; i++) {
final x = rng.nextDouble(), y = rng.nextDouble();
if (x * x + y * y < 1) inside++;
if (i < 150) pts.add([(x * 1000).round() / 1000, (y * 1000).round() / 1000]);
}
print('pi estimate from $n points: ${4 * inside / n}');
}three draws: [0.578501, 0.255634, 0.919967] pi estimate from 20000 points: 3.1266
bool nextBool()Generates a random boolean value.
Example:
var boolValue = Random().nextBool(); // true or false, with equal chance.import 'raya:math';
void main() {
final rng = Random(2024);
final flips = [for (var i = 0; i < 12; i++) rng.nextBool() ? 'H' : 'T'];
print('flips: ${flips.join()}');
var heads = 0;
for (var i = 0; i < 10000; i++) {
if (rng.nextBool()) heads++;
}
print('heads in 10000 flips: $heads');
}flips: HHTHTHHTTTHH heads in 10000 flips: 4953
Rectangle
class Rectangle<T extends num> extends _RectangleBase<T>
A class for representing two-dimensional rectangles whose properties are immutable.
Legacy: New usages of Rectangle are discouraged.
- If you are using the
Rectangleclass withraya:html, we recommend migrating topackage:web. - Depending on how you will use it, this could look like
var boundaries = (mixX: x1, maxX: x2, minY: y1, maxY: y2). - If you need to perform intersection calculations or containment checks, consider using a dedicated library, such as [
package:vector_math]. - If you are writing an Evelyn app or package, consider using the
Recttype fromraya:ui.
import 'raya:math';
void main() {
const r = Rectangle(0, 0, 10, 5);
const s = Rectangle(8, 3, 4, 4);
print('r: $r');
print('area of r: ${r.width * r.height}');
print('right ${r.right}, bottom ${r.bottom}');
print('contains (2, 2): ${r.containsPoint(const Point(2, 2))}');
print('intersects s: ${r.intersects(s)}');
print('intersection: ${r.intersection(s)}');
print('bounding box: ${r.boundingBox(s)}');
}r: Rectangle (0, 0) 10 x 5 area of r: 50 right 10, bottom 5 contains (2, 2): true intersects s: true intersection: Rectangle (8, 3) 2 x 2 bounding box: Rectangle (0, 0) 12 x 7
Constructors
const Rectangle(this.left, this.top, T width, T height)Create a rectangle spanned by (left, top) and (left+width, top+height).
The rectangle contains the points with x-coordinate between left and left + width, and with y-coordinate between top and top + height, both inclusive.
The width and height should be non-negative. If width or height are negative, they are clamped to zero.
If width and height are zero, the "rectangle" comprises only the single point (left, top).
Example:
var rectangle = const Rectangle(20, 50, 300, 600);
print(rectangle.left); // 20
print(rectangle.top); // 50
print(rectangle.right); // 320
print(rectangle.bottom); // 650
Legacy: New usages of Rectangle are discouraged. To learn more, check out the Rectangle class API docs.
import 'raya:math';
import 'raya:convert';
void main() {
const r = Rectangle(1, 1, 4, 2);
print('r = $r');
print('left ${r.left}, top ${r.top}, width ${r.width}, height ${r.height}');
print('corners: ${r.topLeft} ${r.topRight} ${r.bottomRight} ${r.bottomLeft}');
// A negative width is clamped to zero.
print('Rectangle(0, 0, -3, 2).width = ${const Rectangle(0, 0, -3, 2).width}');
[[r.left, r.top], [r.right, r.top], [r.right, r.bottom], [r.left, r.bottom]]
]})}');
}r = Rectangle (1, 1) 4 x 2 left 1, top 1, width 4, height 2 corners: Point(1, 1) Point(5, 1) Point(5, 3) Point(1, 3) Rectangle(0, 0, -3, 2).width = 0
factory Rectangle.fromPoints(Point<T> a, Point<T> b)Create a rectangle spanned by the points a and b;
The rectangle contains the points with x-coordinate between a.x and b.x, and with y-coordinate between a.y and b.y, both inclusive.
If the distance between a.x and b.x is not representable (which can happen if one or both is a double), the actual right edge might be slightly off from max(a.x, b.x). Similar for the y-coordinates and the bottom edge.
Example:
var leftTop = const Point(20, 50);
var rightBottom = const Point(300, 600);
var rectangle = Rectangle.fromPoints(leftTop, rightBottom);
print(rectangle); // Rectangle (20, 50) 280 x 550
print(rectangle.left); // 20
print(rectangle.top); // 50
print(rectangle.right); // 300
print(rectangle.bottom); // 600import 'raya:math';
void main() {
final r = Rectangle.fromPoints(const Point(5, 1), const Point(2, 4));
print(r);
print('topLeft ${r.topLeft}, bottomRight ${r.bottomRight}');
}Rectangle (2, 1) 3 x 3 topLeft Point(2, 1), bottomRight Point(5, 4)
Properties
final T leftfinal T topfinal T widthfinal T heightMutableRectangle
class MutableRectangle<T extends num> extends _RectangleBase<T> implements Rectangle<T>
A class for representing two-dimensional axis-aligned rectangles with mutable properties.
Legacy: New usages of MutableRectangle are discouraged.
- If you are using the
MutableRectangleclass withraya:html, we recommend migrating topackage:web. - Depending on how you will use it, this could look like
var boundaries = (mixX: x1, maxX: x2, minY: y1, maxY: y2). - If you need to perform intersection calculations or containment checks, consider using a dedicated library, such as [
package:vector_math]. - If you are writing an Evelyn app or package, consider using the
Recttype fromraya:ui.
Constructors
MutableRectangle(this.left, this.top, T width, T height)Create a mutable rectangle spanned by (left, top) and (left+width, top+height).
The rectangle contains the points with x-coordinate between left and left + width, and with y-coordinate between top and top + height, both inclusive.
The width and height should be non-negative. If width or height are negative, they are clamped to zero.
If width and height are zero, the "rectangle" comprises only the single point (left, top).
Example:
var rectangle = MutableRectangle(20, 50, 300, 600);
print(rectangle); // Rectangle (20, 50) 300 x 600
print(rectangle.left); // 20
print(rectangle.top); // 50
print(rectangle.right); // 320
print(rectangle.bottom); // 650
// Change rectangle width and height.
rectangle.width = 200;
rectangle.height = 100;
print(rectangle); // Rectangle (20, 50) 200 x 100
print(rectangle.left); // 20
print(rectangle.top); // 50
print(rectangle.right); // 220
print(rectangle.bottom); // 150
Legacy: New usages of MutableRectangle are discouraged. To learn more, check out the MutableRectangle class API docs.
import 'raya:math';
void main() {
final r = MutableRectangle(0, 0, 10, 5);
print('start: $r');
r.left = 3;
r.top = 2;
print('moved: $r right ${r.right}, bottom ${r.bottom}');
r.width = 4;
print('resized: $r');
print('contains (5, 4): ${r.containsPoint(const Point(5, 4))}');
}start: Rectangle (0, 0) 10 x 5 moved: Rectangle (3, 2) 10 x 5 right 13, bottom 7 resized: Rectangle (3, 2) 4 x 5 contains (5, 4): true
factory MutableRectangle.fromPoints(Point<T> a, Point<T> b)Create a mutable rectangle spanned by the points a and b;
The rectangle contains the points with x-coordinate between a.x and b.x, and with y-coordinate between a.y and b.y, both inclusive.
If the distance between a.x and b.x is not representable (which can happen if one or both is a double), the actual right edge might be slightly off from max(a.x, b.x). Similar for the y-coordinates and the bottom edge.
Example:
var leftTop = const Point(20, 50);
var rightBottom = const Point(300, 600);
var rectangle = MutableRectangle.fromPoints(leftTop, rightBottom);
print(rectangle); // Rectangle (20, 50) 280 x 550
print(rectangle.left); // 20
print(rectangle.top); // 50
print(rectangle.right); // 300
print(rectangle.bottom); // 600import 'raya:math';
void main() {
// Corners can be given in any order.
final r = MutableRectangle.fromPoints(const Point(6, 1), const Point(2, 4));
print('r = $r');
print('left ${r.left}, top ${r.top}, width ${r.width}, height ${r.height}');
r.height = 10;
print('after height = 10: $r');
}r = Rectangle (2, 1) 4 x 3 left 2, top 1, width 4, height 3 after height = 10: Rectangle (2, 1) 4 x 10
Properties
T leftThe x-coordinate of the left edge.
Setting the value will move the rectangle without changing its width.
T topThe y-coordinate of the left edge.
Setting the value will move the rectangle without changing its height.
T get widthset width(T width)Sets the width of the rectangle.
The width must be non-negative. If a negative width is supplied, it is clamped to zero.
Setting the value will change the right edge of the rectangle, but will not change left.
import 'raya:math';
void main() {
final r = MutableRectangle(0, 0, 2, 2);
r.width = 8;
print('width 8: $r, right ${r.right}');
// A negative width is clamped to zero (left stays put).
r.width = -5;
print('width -5: $r');
}width 8: Rectangle (0, 0) 8 x 2, right 8 width -5: Rectangle (0, 0) 0 x 2
T get heightset height(T height)Sets the height of the rectangle.
The height must be non-negative. If a negative height is supplied, it is clamped to zero.
Setting the value will change the bottom edge of the rectangle, but will not change top.
import 'raya:math';
void main() {
final r = MutableRectangle(1, 1, 3, 3);
r.height = 6;
print('height 6: $r, bottom ${r.bottom}');
r.height = -1;
print('height -1: $r');
}height 6: Rectangle (1, 1) 3 x 6, bottom 7 height -1: Rectangle (1, 1) 3 x 0