Introduction
Dart can also perform mathematical operations. Dart has created a dart:math package for mathematics enthusiasts to handle various operations in mathematics. The dart:math package provides sine, cosine, maximum, minimum and random number operations.
Let's take a look at what the dart:math package can do.
Dart: The composition of the math package
If you check the source code of dart:math, you will find that the dart:math package is actually very simple. There are only 4 files in it. They are:
math.dart, random.dart, point.dart and rectangle.dart.
The latter two files are mainly related to two-dimensional coordinates, so I won’t explain them in detail here.
We often use the first two files, math and random.
math
Math defines some constants commonly used in mathematical operations, such as:
const double e = 2.718281828459045;
const double ln10 = 2.302585092994046;
const double ln2 = 0.6931471805599453;
const double log2e = 1.4426950408889634;
const double log10e = 0.4342944819032518;
const double pi = 3.1415926535897932;
const double sqrt1_2 = 0.7071067811865476;
const double sqrt2 = 1.4142135623730951;
Calculate the maximum and minimum values:
assert(max(18, 20) == 20);
assert(min(18, 20) == 18);
Use trigonometric functions:
assert(cos(pi) == -1.0);
var degrees = 30;
var radians = degrees * (pi / 180);
var sinOf30degrees = sin(radians);
assert((sinOf30degrees - 0.5).abs() < 0.01);
Random
The random package in dart provides some useful methods for generating random numbers. Let’s first look at the definition of the Random class:
abstract class Random {
external factory Random([int? seed]);
external factory Random.secure();
int nextInt(int max);
double nextDouble();
bool nextBool();
}
We can use the nextInt, nextDouble and nextBool provided in Random to generate the corresponding random numbers:
var random = Random();
random.nextDouble();
random.nextInt(10);
random.nextBool();
By default, Random generates pseudo-random numbers. To generate more secure random numbers, such as random numbers in the cryptographic sense, Random also has a more secure implementation Random.secure().
Summarize
The above is the introduction of the math library in dart.
This article has been included in http://www.flydean.com/18-dart-math/
The most popular interpretation, the most profound dry goods, the most concise tutorial, and many tips you don't know are waiting for you to discover!
Welcome to pay attention to my official account: "programs, those things", know the technology, know you better!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。