JavaScript/Math/LN2
表示
< JavaScript | Math
Math.LN2
は、2の自然対数(底が e
の対数)を表す定数です。この値は、約 0.6931471805599453
です[1]。
例
[編集]2の自然対数を使用するプログラム
[編集]以下のプログラムは、Math.LN2
を使用して対数計算を行います。
constf=p=>{for(;;){a=prompt(`${p}は何ですか?`);if(!isNaN(a))returna;alert(`${p}に、入力ミスがあります。 "${a}"`);}}for(;;){constx=f("値");constlog2=Math.log(x)/Math.LN2;if(!isNaN(log2)){alert(`${x} の2を底とする対数は ${log2.toFixed(3)} です。`);break;}alert("入力が大きすぎます。");}
このプログラムでは、Math.LN2
を使用して2を底とする対数を計算しています。ユーザーが入力した値が NaN
や Infinity
の場合、適切に処理されます。
2の自然対数を使用したグラフの描画
[編集]以下のプログラムは、Math.LN2
を使用して対数関数のグラフを描画します。
constcanvas=document.createElement('canvas');document.body.appendChild(canvas);constctx=canvas.getContext('2d');canvas.width=800;canvas.height=400;constxScale=canvas.width/10;constyScale=canvas.height/5;ctx.beginPath();ctx.moveTo(0,canvas.height);for(letx=0.1;x<=10;x+=0.1){consty=Math.log(x)/Math.LN2;constcanvasX=x*xScale;constcanvasY=canvas.height-y*yScale;ctx.lineTo(canvasX,canvasY);}ctx.strokeStyle='blue';ctx.lineWidth=2;ctx.stroke();
このプログラムでは、Math.LN2
を使用して2を底とする対数関数のグラフを描画しています。xScale
と yScale
は、グラフのスケーリングを調整するための変数です。
注意点
[編集]- 定数の値:
Math.LN2
は、約0.6931471805599453
の値を持つ定数です。 - 精度: 浮動小数点演算の特性上、
Math.LN2
の値には微小な誤差が含まれることがあります。
脚註
[編集]- ^これは、数学的には として定義されます。