0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Roadmap.shで学ぶFlutter - Advanced Dart - [Core Libraries③:math]

Posted at

導入

roadmap.shのFlutterのAdvanced Dart Core Librariesの3本目です。

dart:math

dart:mathライブラリは、正弦や余弦、最大値と最小値、円周率(pi)やネイピア数(e)などの定数を利用できる機能を含んでいます。このライブラリをアプリで使用するには、dart:mathをインポートしてから利用することになります。

import 'dart:math';

三角関数

Mathライブラリは基本的な三角関数を提供しています。

// 余弦
assert(cos(pi) == -1.0);

// 正弦
var degrees = 30;
var radians = degrees * (pi / 180);
// radiansは0.52359になります。
var sinOf30degrees = sin(radians);
// sin 30° = 0.5
assert((sinOf30degrees - 0.5).abs() < 0.01);

これらの関数は度数ではなくラジアンを使用します。

最大値と最小値

Mathライブラリはmax()min()メソッドを提供しています。

assert(max(1, 1000) == 1000);
assert(min(1, -1000) == -1000);

数学定数

Mathライブラリには、一般的に利用される定数(pi, eなど)も含まれます。

// Mathライブラリで他の定数も参照できます。
print(e); // 2.718281828459045
print(pi); // 3.141592653589793
print(sqrt2); // 1.4142135623730951

乱数

Randomクラスを使用して乱数を生成できます。Randomコンストラクタにシードを設定することも可能です。

var random = Random();
random.nextDouble(); // 0.0と1.0の間の数:[0, 1)
random.nextInt(10); // 0から9の間の数。

ランダムなブール値も生成できます。

var random = Random();
random.nextBool(); // trueまたはfalse

デフォルトのRandom実装は、暗号学的に安全でない擬似乱数ビットのストリームを提供します。暗号学的に安全な乱数生成器を作成するには、Random.secure()コンストラクタを使用してください。

終わりに

今回は、dart:mathライブラリについて紹介しました。このライブラリは、数学的な計算や定数、乱数生成など、さまざまな機能を提供しています。特に三角関数や数学定数、乱数の生成は、多くのアプリケーションで必要となる基本的な要素です。これらの機能を利用することで、より複雑なアルゴリズムやシミュレーションを簡単に実装することができます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?