JavaScript/Math/PI
表示
< JavaScript | Math
Math.PI
は、円周率(π)を表す定数です。この値は、約 3.141592653589793
です[1]。
例
[編集]円周率を使用するプログラム
[編集]以下のプログラムは、Math.PI
を使用して円の面積を計算します。
const f = p => { for (;;) { a = prompt(`${p}は何ですか?`); if (!isNaN(a) && a > 0) return a; alert(`${p}に、入力ミスがあります。 "${a}"`); } } for (;;) { const r = f("半径"); const area = Math.PI * r ** 2; if (!isNaN(area)) { alert(`半径 ${r} の円の面積は ${area.toFixed(3)} です。`); break; } alert("入力が大きすぎます。"); }
このプログラムでは、Math.PI
を使用して円の面積を計算しています。ユーザーが入力した値が NaN
や Infinity
の場合、適切に処理されます。
円周率を使用したグラフの描画
[編集]以下のプログラムは、Math.PI
を使用して正弦関数のグラフを描画します。
const canvas = document.createElement('canvas'); document.body.appendChild(canvas); const ctx = canvas.getContext('2d'); canvas.width = 800; canvas.height = 400; const xScale = canvas.width / (2 * Math.PI); const yScale = canvas.height / 2; ctx.beginPath(); ctx.moveTo(0, canvas.height / 2); for (let x = 0; x <= 2 * Math.PI; x += 0.1) { const y = Math.sin(x); const canvasX = x * xScale; const canvasY = canvas.height / 2 - y * yScale; ctx.lineTo(canvasX, canvasY); } ctx.strokeStyle = 'blue'; ctx.lineWidth = 2; ctx.stroke();
このプログラムでは、Math.PI
を使用して正弦関数のグラフを描画しています。xScale
と yScale
は、グラフのスケーリングを調整するための変数です。
注意点
[編集]- 定数の値:
Math.PI
は、約3.141592653589793
の値を持つ定数です。 - 精度: 浮動小数点演算の特性上、
Math.PI
の値には微小な誤差が含まれることがあります。
脚註
[編集]- ^ これは、数学的には円の周長と直径の比として定義されます。
外部リンク
[編集]