この関数の平方根を近似したい。Math.sqrt(float); 結果は、ポイントの後の小数点以下の桁数が最大 6 または 7 である別の float になるはずです。
4037 次
3 に答える
5
より小さく、より扱いやすい数値を取得したい場合は、次のようにtoFixed
メソッドを使用できます。
var x = 0.343423409554534598959;
console.log( x.toFixed(3) )
// outputs 0.343
平方根全体を計算して桁数の精度を捨てるという考えに耐えられない場合は、近似法を使用できます。ただし、時期尚早の最適化は諸悪の根源であることに注意してください。KISS のイディオムはこれに反します。
ヘロンの方法は次のとおりです。
function sqrt(num) {
// Create an initial guess by simply dividing by 3.
var lastGuess, guess = num / 3;
// Loop until a good enough approximation is found.
do {
lastGuess = guess; // store the previous guess
// find a new guess by averaging the old one with
// the original number divided by the old guess.
guess = (num / guess + guess) / 2;
// Loop again if the product isn't close enough to
// the original number.
} while(Math.abs(lastGuess - guess) > 5e-15);
return guess; // return the approximate square root
};
さらに、このウィキペディアのページから実装するのは簡単です。
于 2013-03-25T11:18:19.510 に答える
0
を使用して平方根を丸めることができます
(double)Math.round(float * Math.pow(10,r)) /Math.pow(10,r);
ここで、r
はドットの後に出力したい数字です。
このようなプログラムを試してください
float f = 0.123f;
double d = Math.sqrt(f);
d = (double)Math.round(d * Math.pow(10,5)) /Math.pow(10,5);
System.out.println(d);
出力: 0.35071
于 2013-03-25T15:42:32.553 に答える
0
スタックオーバーフローの閲覧 しばらく前にこのコードを見つけましたが、これは望ましい精度に近いものです (このコードは私のものではありません。^C^V-ed です)
function round (value, precision, mode)
{
precision |= 0; // making sure precision is integer
var m = Math.pow(10, precision);
value *= m;
var sgn = (value > 0) | - (value < 0); // sign of the number
var isHalf = value % 1 === 0.5 * sgn;
var f = Math.floor(value);
if (isHalf)
switch (mode) {
case 'PHP_ROUND_HALF_DOWN':
value = f + (sgn < 0); // rounds .5 toward zero
break;
case 'PHP_ROUND_HALF_EVEN':
value = f + (f % 2 * sgn); // rouds .5 towards the next even integer
break;
case 'PHP_ROUND_HALF_ODD':
value = f + !(f % 2); // rounds .5 towards the next odd integer
break;
default:
value = f + (sgn > 0); // rounds .5 away from zero
}
return (isHalf ? value : Math.round(value)) / m;
}
于 2013-03-25T11:20:36.807 に答える