コンテンツにスキップ

JavaScript/Math/PI

出典: フリー教科書『ウィキブックス(Wikibooks)』

Math.PI は、円周率(π)を表す定数です。この値は、約 3.141592653589793 です[1]

[編集]

円周率を使用するプログラム

[編集]

以下のプログラムは、Math.PI を使用して円の面積を計算します。

constf=p=>{for(;;){a=prompt(`${p}は何ですか?`);if(!isNaN(a)&&a>0)returna;alert(`${p}に、入力ミスがあります。 "${a}"`);}}for(;;){constr=f("半径");constarea=Math.PI*r**2;if(!isNaN(area)){alert(`半径 ${r} の円の面積は ${area.toFixed(3)} です。`);break;}alert("入力が大きすぎます。");}

このプログラムでは、Math.PI を使用して円の面積を計算しています。ユーザーが入力した値が NaNInfinity の場合、適切に処理されます。

円周率を使用したグラフの描画

[編集]

以下のプログラムは、Math.PI を使用して正弦関数のグラフを描画します。

constcanvas=document.createElement('canvas');document.body.appendChild(canvas);constctx=canvas.getContext('2d');canvas.width=800;canvas.height=400;constxScale=canvas.width/(2*Math.PI);constyScale=canvas.height/2;ctx.beginPath();ctx.moveTo(0,canvas.height/2);for(letx=0;x<=2*Math.PI;x+=0.1){consty=Math.sin(x);constcanvasX=x*xScale;constcanvasY=canvas.height/2-y*yScale;ctx.lineTo(canvasX,canvasY);}ctx.strokeStyle='blue';ctx.lineWidth=2;ctx.stroke();

このプログラムでは、Math.PI を使用して正弦関数のグラフを描画しています。xScaleyScale は、グラフのスケーリングを調整するための変数です。

注意点

[編集]
  • 定数の値: Math.PI は、約 3.141592653589793 の値を持つ定数です。
  • 精度: 浮動小数点演算の特性上、Math.PI の値には微小な誤差が含まれることがあります。

脚註

[編集]
  1. ^これは、数学的には円の周長と直径の比として定義されます。

外部リンク

[編集]


close