The Dart math library is a powerful tool for performing mathematical operations in your Dart programs. It provides a wide range of functions and constants for common mathematical tasks.
To use the math library, you need to import it at the beginning of your Dart file:
import 'dart:math';
Here are some frequently used functions from the math library:
sqrt(x)
: Calculates the square root of xpow(x, y)
: Raises x to the power of ymax(a, b)
: Returns the larger of a and bmin(a, b)
: Returns the smaller of a and bsin(x)
, cos(x)
, tan(x)
: Trigonometric functions
import 'dart:math';
void main() {
print(sqrt(16)); // Output: 4.0
print(pow(2, 3)); // Output: 8.0
print(max(5, 3)); // Output: 5
}
import 'dart:math';
void main() {
print(sin(pi / 2)); // Output: 1.0
print(cos(pi)); // Output: -1.0
print(tan(pi / 4)); // Output: 0.9999999999999999
}
The math library includes a Random
class for generating random numbers. It's particularly useful for simulations and games.
import 'dart:math';
void main() {
var random = Random();
print(random.nextInt(100)); // Random integer between 0 and 99
print(random.nextDouble()); // Random double between 0.0 and 1.0
}
To further enhance your Dart programming skills, explore these related topics:
The Dart math library is an essential tool for any developer working with mathematical operations. By mastering its functions, you'll be able to handle complex calculations with ease in your Dart programs.