Math

suggest change

Basic arithmetic is built into Dart's num, int and double types. Everything beyond that (constants like pi, square roots, powers, logarithms, trigonometry, min and max) lives in the dart:math library, which ships with the SDK. There is nothing to add to pubspec.yaml.

This article covers:

Arithmetic operators (/, ~/, %, remainder()) are described in Operators. For numbers bigger than 64 bits see BigInt, and for Random see Random numbers.

The examples were run with Dart 3.13.

Importing dart:math and constants

dart:math exports top-level functions and constants. Many programs import it with a prefix, because names like min, max, e and log are short and easy to shadow:

import 'dart:math' as math;

double circleArea(double r) => math.pi * r * r;

Without a prefix you write pi and sqrt(2) directly. Both styles are common, and this article uses whichever reads better in each example.

The library defines these double constants:

import 'dart:math';

void main() {
  print(pi);
  print(e);
  print(sqrt2);
  print(sqrt1_2);
  print(ln2);
  print(ln10);
  print(log2e);
  print(log10e);
}

Output:

3.141592653589793
2.718281828459045
1.4142135623730951
0.7071067811865476
0.6931471805599453
2.302585092994046
1.4426950408889634
0.4342944819032518

pi is the ratio of a circle's circumference to its diameter, e is the base of the natural logarithm, sqrt1_2 is the square root of 1/2, and log2e / log10e are the base-2 and base-10 logarithms of e.

abs, sign, min, max and clamp

Some helpers are methods on num (so they work on both int and double), and some are top-level functions in dart:math:

import 'dart:math' as math;

void main() {
  print((-7).abs()); // 7
  print((-2.5).abs()); // 2.5
  print((-7).sign); // -1
  print(0.0.sign); // 0.0
  print(3.2.sign); // 1.0

  print(math.min(3, 8)); // 3
  print(math.max(3, 8.5)); // 8.5
  print(math.max(double.nan, 1)); // NaN

  print(15.clamp(0, 10)); // 10
  print((-3).clamp(0, 10)); // 0
  print(0.75.clamp(0.0, 0.5)); // 0.5

  print(10.isEven); // true
  print(7.isOdd); // true
  print(12.gcd(18)); // 6
}

A few things to note:

math.min and math.max take exactly two arguments. To find the smallest or largest element of a list, pass them to reduce:

import 'dart:math' as math;

void main() {
  final values = [4, 9, 1, 7];
  print(values.reduce(math.min)); // 1
  print(values.reduce(math.max)); // 9

  final scores = [72.5, 88.0, 91.25];
  print(scores.reduce(math.max)); // 91.25
}

reduce throws on an empty list. If the list may be empty, check isEmpty first, or use minOrNull / maxOrNull from package:collection.

Rounding

double has four rounding methods that return an int, and four matching ones that return a double:

void main() {
  for (final x in [2.5, 2.4, -2.5, -2.6]) {
    print('$x: round=${x.round()} floor=${x.floor()} '
        'ceil=${x.ceil()} truncate=${x.truncate()}');
  }

  print(2.7.roundToDouble()); // 3.0
  print(2.7.floorToDouble()); // 2.0
  print(7.round().runtimeType); // int
}

Output:

2.5: round=3 floor=2 ceil=3 truncate=2
2.4: round=2 floor=2 ceil=3 truncate=2
-2.5: round=-3 floor=-3 ceil=-2 truncate=-2
-2.6: round=-3 floor=-3 ceil=-2 truncate=-2
3.0
2.0
int

The int-returning versions throw UnsupportedError for NaN and infinity. The ...ToDouble() versions don't: they return NaN or infinity unchanged.

These methods also exist on int, where they return the value itself.

Rounding to N decimal places

There is no round(x, 2). To get a number, multiply, round and divide. To get a string for display, use toStringAsFixed:

import 'dart:math' as math;

double roundTo(double value, int places) {
  final factor = math.pow(10, places);
  return (value * factor).round() / factor;
}

void main() {
  print(roundTo(3.14159, 2)); // 3.14
  print(roundTo(1234.5678, -2)); // 1200.0
  print(3.14159.toStringAsFixed(2)); // 3.14
  print(2.0.toStringAsFixed(2)); // 2.00

  // 2.675 is really 2.67499999999999982236431605997495353221893310546875
  print(2.675.toStringAsFixed(2));
  print(roundTo(2.675, 2));
  print(1.005.toStringAsFixed(2));
}

Output:

3.14
1200.0
3.14
2.00
2.67
2.68
1.00

The last three lines show a common surprise. 2.675 can't be stored exactly in binary floating point. The nearest double is slightly less than 2.675, so toStringAsFixed(2) correctly gives 2.67. The multiply-and-round helper gives 2.68 only because 2.675 * 100 happens to round up to exactly 267.5. Neither approach gives exact decimal rounding for every input.

If exact decimal results matter, as with money, don't use double at all. Store amounts as an integer number of cents (or as a scaled BigInt, see BigInt), or use the decimal package.

Powers and roots

pow(x, exponent) returns num. When both arguments are int and the exponent is non-negative, the result is an int. Otherwise it's a double:

import 'dart:math';

void main() {
  print(pow(2, 10)); // 1024
  print(pow(2, 10).runtimeType); // int
  print(pow(2, 0.5)); // 1.4142135623730951
  print(pow(2, -1)); // 0.5
  print(pow(2.0, 3)); // 8.0

  final int kib = pow(2, 10).toInt();
  print(kib);

  print(sqrt(16)); // 4.0
  print(sqrt(2));
  print(sqrt(-1)); // NaN
  print(pow(27, 1 / 3)); // cube root
  print(pow(2, 64)); // wraps to 0 on the VM
}

Output:

1024
int
1.4142135623730951
0.5
8.0
1024
4.0
1.4142135623730951
NaN
3.0
0

Because pow is declared to return num, assigning it to an int variable needs .toInt() (or as int).

Integer pow wraps around on overflow, just like *, so pow(2, 64) is 0 on the Dart VM. Use BigInt.pow when the result might not fit in 64 bits.

sqrt always returns a double, and the square root of a negative number is NaN rather than an exception. There is no cbrt. pow(x, 1 / 3) works for positive x, but returns NaN for negative x, because 1 / 3 isn't exactly one third. For a negative cube root, use -pow(-x, 1 / 3).

Exponents and logarithms

exp(x) computes e to the power of x, and log(x) is the natural logarithm. There are no log2 or log10 functions. Divide by ln2 or ln10 instead:

import 'dart:math';

double logBase(num x, num base) => log(x) / log(base);

void main() {
  print(exp(1)); // e
  print(log(e)); // 1.0: natural log
  print(log(100) / ln10); // log10
  print(log(1024) / ln2); // log2
  print(logBase(1000, 10));
  print(log(0)); // -Infinity
  print(log(-1)); // NaN

  // the exact way for integer log2
  print(1024.bitLength - 1); // 10
}

Output:

2.718281828459045
1.0
2.0
10.0
2.9999999999999996
-Infinity
NaN
10

Logarithms in other bases are computed in floating point, so they are not always exact: log(1000) / log(10) is 2.9999999999999996, and calling .floor() on it would give 2. For integer base-2 logarithms, use bitLength, which is exact. For other integer bases, a loop with integer multiplication is the safe choice.

Trigonometry

sin, cos, tan, asin, acos, atan and atan2 all work with radians. Convert degrees to radians by multiplying by pi / 180:

import 'dart:math';

double toRadians(double degrees) => degrees * pi / 180;
double toDegrees(double radians) => radians * 180 / pi;

void main() {
  print(sin(toRadians(30)));
  print(cos(toRadians(60)));
  print(tan(toRadians(45)));
  print(sin(pi)); // not exactly 0

  print(toDegrees(asin(0.5)));
  print(toDegrees(acos(0.5)));
  print(toDegrees(atan(1)));

  // atan2 picks the right quadrant
  print(toDegrees(atan2(1, -1))); // 135
  print(toDegrees(atan(1 / -1))); // -45: wrong quadrant
}

Output:

0.49999999999999994
0.5000000000000001
0.9999999999999999
1.2246467991473532e-16
30.000000000000004
60.00000000000001
45.0
135.0
-45.0

Results are floating point, so sin(pi) is a tiny number instead of 0, and asin(0.5) in degrees is 30.000000000000004. Round the output or compare with a tolerance (see Floating-point precision).

Use atan2(y, x) instead of atan(y / x) to get the angle of a vector. It takes the signs of both arguments into account, so it returns the correct quadrant in the range -pi to pi, and it handles x == 0 without a division by zero. Note the argument order: y comes first.

asin and acos return NaN for arguments outside -1 to 1. Dart has no hyperbolic functions (sinh, cosh, tanh), but they are easy to write with exp, for example sinh(x) = (exp(x) - exp(-x)) / 2.

Interpolation and angle wrapping

A few small helpers come up often in graphics, games and UI code:

import 'dart:math';

double lerp(double a, double b, double t) => a + (b - a) * t;

double mapRange(double x, double inMin, double inMax, double outMin,
        double outMax) =>
    outMin + (x - inMin) * (outMax - outMin) / (inMax - inMin);

// normalize an angle to the range [0, 360)
double wrapDegrees(double d) => d % 360;

// normalize radians to [-pi, pi)
double wrapRadians(double r) => (r + pi) % (2 * pi) - pi;

void main() {
  print(lerp(10, 20, 0.25)); // 12.5
  print(mapRange(75, 0, 100, 0, 255)); // 191.25
  print(mapRange(68, 32, 212, 0, 100)); // Fahrenheit to Celsius: 20.0
  print(wrapDegrees(-90)); // 270.0
  print(wrapDegrees(725)); // 5.0
  print(wrapRadians(3 * pi / 2)); // -pi/2
}

Output:

12.5
191.25
20.0
270.0
5.0
-1.5707963267948966

wrapDegrees and wrapRadians work for negative angles without extra code because Dart's % always returns a non-negative result for a positive divisor.

Point and Rectangle

dart:math also has two small geometry classes, Point<T extends num> and Rectangle<T extends num>. There is no hypot function, but Point.distanceTo and Point.magnitude compute the same thing:

import 'dart:math';

double hypot(double x, double y) => sqrt(x * x + y * y);

void main() {
  print(hypot(3, 4)); // 5.0

  const a = Point(1, 2);
  const b = Point(4, 6);
  print(a.distanceTo(b)); // 5.0
  print(a + b); // Point(5, 8)
  print(b - a); // Point(3, 4)
  print(a * 3); // Point(3, 6)
  print((b - a).magnitude); // 5.0

  const r = Rectangle(0, 0, 10, 5);
  print(r.containsPoint(const Point(3, 4))); // true
  print(r.containsPoint(const Point(11, 4))); // false
  final other = Rectangle(8, 2, 6, 6);
  print(r.intersection(other));
  print(r.boundingBox(other));
  print(r.intersects(other));
}

Output:

5.0
5.0
Point(5, 8)
Point(3, 4)
Point(3, 6)
5.0
true
false
Rectangle (8, 2) 2 x 3
Rectangle (0, 0) 14 x 8
true

Rectangle(left, top, width, height) uses screen coordinates, where top is the smaller y value. MutableRectangle is a version whose fields can be changed. Both classes are generic, so Point(1, 2) is a Point<int> and Point(1.5, 2) is a Point<num>.

These classes are fine for simple cases. For real vector math (3D, matrices, quaternions), use a package such as vector_math.

Floating-point precision

double is a 64-bit IEEE 754 floating-point number, the same as double in C and Java and number in JavaScript. Most decimal fractions, including 0.1, can't be represented exactly, so small errors appear and accumulate:

import 'dart:math' as math;

bool nearlyEqual(double a, double b,
    {double relTol = 1e-9, double absTol = 1e-12}) {
  final diff = (a - b).abs();
  return diff <= absTol || diff <= relTol * math.max(a.abs(), b.abs());
}

void main() {
  print(0.1 + 0.2); // 0.30000000000000004
  print(0.1 + 0.2 == 0.3); // false
  print(nearlyEqual(0.1 + 0.2, 0.3)); // true
  print(nearlyEqual(1e-20, 2e-20)); // true: both are ~0
  print(nearlyEqual(1000000.0, 1000001.0)); // false

  var sum = 0.0;
  for (var i = 0; i < 10; i++) {
    sum += 0.1;
  }
  print(sum); // 0.9999999999999999

  // count in integers, convert at the end
  print(List.generate(5, (i) => i / 10)); // [0.0, 0.1, 0.2, 0.3, 0.4]
}

Output:

0.30000000000000004
false
true
true
false
0.9999999999999999
[0.0, 0.1, 0.2, 0.3, 0.4]

Rules of thumb:

Infinity, NaN and limits

void main() {
  print(double.maxFinite); // 1.7976931348623157e+308
  print(double.minPositive); // 5e-324
  print(double.infinity);
  print(double.negativeInfinity);
  print(double.nan);

  final x = 0 / 0;
  print(x == x); // false
  print(x.isNaN); // true
  print((1 / 0).isInfinite); // true
  print(1e308 * 10); // Infinity
  print(5.0.isFinite); // true

  print(-0.0 == 0.0); // true
  print((-0.0).isNegative); // true

  // 64-bit int on the VM
  const maxInt = 0x7FFFFFFFFFFFFFFF;
  print(maxInt); // 9223372036854775807
  print(maxInt + 1); // -9223372036854775808

  // doubles hold integers exactly only up to 2^53
  print(9007199254740993.toDouble()); // 9007199254740992.0
}

Output:

1.7976931348623157e+308
5e-324
Infinity
-Infinity
NaN
false
true
true
Infinity
true
true
true
9223372036854775807
-9223372036854775808
9007199254740992.0

When Dart is compiled to JavaScript, int values are JavaScript numbers. They are exact only up to 2^53, and they don't wrap at 64 bits. Code that relies on 64-bit wrapping behaves differently on the web, so use BigInt there too.

Integer math

int has gcd, modPow and modInverse built in. Other common helpers are a few lines each:

int lcm(int a, int b) => a == 0 || b == 0 ? 0 : (a ~/ a.gcd(b) * b).abs();

int ipow(int base, int exp) {
  var result = 1;
  while (exp > 0) {
    if (exp.isOdd) result *= base;
    base *= base;
    exp >>= 1;
  }
  return result;
}

int isqrt(int n) {
  if (n < 0) throw ArgumentError.value(n, 'n', 'must be non-negative');
  var x = n;
  var y = (x + 1) ~/ 2;
  while (y < x) {
    x = y;
    y = (x + n ~/ x) ~/ 2;
  }
  return x;
}

// for positive a and b
int ceilDiv(int a, int b) => (a + b - 1) ~/ b;

void main() {
  print(lcm(4, 6)); // 12
  print([4, 6, 10].reduce(lcm)); // 60
  print(ipow(3, 13)); // 1594323
  print(isqrt(99)); // 9
  print(isqrt(1 << 62)); // 2147483648
  print(ceilDiv(10, 3)); // 4: e.g. pages needed
  print(17.modPow(5, 7)); // 17^5 mod 7 = 5
  print(3.modInverse(11)); // 4, because 3 * 4 = 12 = 1 mod 11
}

Detecting overflow

Dart doesn't report int overflow. If you need to catch it instead of silently getting a wrong result, check after the operation:

int checkedAdd(int a, int b) {
  final r = a + b;
  // overflow happened if both operands have the same sign
  // and the result has a different one
  if ((a ^ r) & (b ^ r) < 0) {
    throw StateError('int overflow: $a + $b');
  }
  return r;
}

int checkedMul(int a, int b) {
  if (a == 0 || b == 0) return 0;
  final r = a * b;
  if (r ~/ b != a || (a == -1 && b == -9223372036854775808)) {
    throw StateError('int overflow: $a * $b');
  }
  return r;
}

void main() {
  print(checkedAdd(1, 2));
  try {
    checkedAdd(9223372036854775807, 1);
  } on StateError catch (e) {
    print(e);
  }
  print(checkedMul(3037000499, 3037000499));
  try {
    checkedMul(3037000500, 3037000500);
  } on StateError catch (e) {
    print(e);
  }
}

Output:

3
Bad state: int overflow: 9223372036854775807 + 1
9223372030926249001
Bad state: int overflow: 3037000500 * 3037000500

3037000499 is the largest number whose square fits in a signed 64-bit int. In most code it's simpler to switch to BigInt whenever values can get that large.

Simple statistics

dart:core has no sum or average for lists. Use fold (or reduce):

import 'dart:math' as math;

double mean(List<num> xs) => xs.fold<num>(0, (a, b) => a + b) / xs.length;

double median(List<num> xs) {
  final s = [...xs]..sort();
  final mid = s.length ~/ 2;
  return s.length.isOdd ? s[mid].toDouble() : (s[mid - 1] + s[mid]) / 2;
}

double stddev(List<num> xs) {
  final m = mean(xs);
  final variance =
      xs.map((x) => math.pow(x - m, 2)).fold<num>(0, (a, b) => a + b) /
          xs.length;
  return math.sqrt(variance);
}

void main() {
  final data = [2, 4, 4, 4, 5, 5, 7, 9];
  print(data.fold<int>(0, (a, b) => a + b)); // 40
  print(mean(data)); // 5.0
  print(median(data)); // 4.5
  print(stddev(data)); // 2.0
  print(mean([1.5, 2.5, 3.25]));
}

Pass the type argument to fold (fold<int> or fold<num>). Without it, Dart can't always infer the type of the accumulator, and you get a compile error like The operator '+' isn't defined for the type 'Object?'.

stddev here is the population standard deviation. For the sample standard deviation, divide by xs.length - 1. package:collection adds sum, average, min and max extensions on iterables of numbers if you'd rather not write these yourself.

Formatting numbers

num has several methods that turn a number into a string:

void main() {
  const x = 1234.5678;
  print(x.toStringAsFixed(1)); // 1234.6
  print(x.toStringAsPrecision(3)); // 1.23e+3
  print(x.toStringAsPrecision(6)); // 1234.57
  print(x.toStringAsExponential(2)); // 1.23e+3
  print(0.000012.toString()); // 0.000012
  print(1e21.toString());
  print(1e20.toString());

  print(255.toRadixString(2)); // 11111111
  print(255.toRadixString(16)); // ff
  print(int.parse('ff', radix: 16)); // 255
  print(42.toString().padLeft(6, '0')); // 000042
  print(num.parse('3.5e2')); // 350.0
  print(num.tryParse('abc')); // null
}

For thousands separators, currencies and locale-specific formats, use NumberFormat from package:intl (see Localization). Parsing strings into numbers is covered in Type conversion.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents