Dart Math Library
Learn Dart through interactive, bite-sized lessons. Build Flutter apps and master modern development.
Start Dart Journey →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.
Importing the Math Library
To use the math library, you need to import it at the beginning of your Dart file:
import 'dart:math';
Key Features
- Basic arithmetic operations
- Trigonometric functions
- Logarithmic and exponential functions
- Random number generation
- Constants like pi and e
Common Functions
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
Examples
Basic Arithmetic
import 'dart:math';
void main() {
print(sqrt(16)); // Output: 4.0
print(pow(2, 3)); // Output: 8.0
print(max(5, 3)); // Output: 5
}
Trigonometry
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
}
Random Number Generation
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
}
Best Practices
- Use the math library for complex calculations to ensure accuracy and efficiency.
- Be aware of potential precision issues with floating-point arithmetic.
- When working with angles, remember that trigonometric functions use radians, not degrees.
Related Concepts
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.