Math 如何在javascript中近似计算浮点的平方根
我想近似这个函数的平方根。sqrt(float); 结果应该是另一个浮点,该点后的十进制位置最大为6或7。Math 如何在javascript中近似计算浮点的平方根,math,Math,我想近似这个函数的平方根。sqrt(float); 结果应该是另一个浮点,该点后的十进制位置最大为6或7。 使用标准的Math.sqrt(float)我得到一个非常大的数字,比如0.3434234095554534598959,这对我来说太多了。如果您只想得到一个更小、更易于管理的数字,可以使用toFixed方法,如下所示: var x = 0.343423409554534598959; console.log( x.toFixed(3) ) // outputs 0.343 如果你不能忍受
使用标准的Math.sqrt(float)我得到一个非常大的数字,比如0.3434234095554534598959,这对我来说太多了。如果您只想得到一个更小、更易于管理的数字,可以使用
toFixed
方法,如下所示:
var x = 0.343423409554534598959;
console.log( x.toFixed(3) )
// outputs 0.343
如果你不能忍受计算整个平方根的想法,而只是丢掉精度的数字,你可以使用近似方法。但要注意,过早优化是万恶之源;“吻”这个成语与此相反
以下是Heron的方法:
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
};
更详细地说,从中实现一个应该是很简单的。浏览stackoverflow我不久前发现了这段代码,它接近所需的精度 (这个代码不是我的,我只是^C^V-ed)
函数舍入(值、精度、模式)
{
精度|=0;//确保精度为整数
var m=数学功率(10,精度);
数值*=m;
var sgn=(值>0)|-(值<0);//数字的符号
var isHalf=值%1==0.5*sgn;
var f=数学下限(值);
如果(isHalf)
开关(模式){
案例“PHP四舍五入”下:
value=f+(sgn<0);//向零舍入.5
打破
案例“PHP四舍五入半偶数”:
value=f+(f%2*sgn);//向下一个偶数整数移动0.5卢布
打破
案例“PHP\u ROUND\u HALF\u ODD”:
value=f+!(f%2);//向下一个奇数整数舍入.5
打破
违约:
value=f+(sgn>0);//舍入0.5
}
返回值(isHalf?值:数学四舍五入(值))/m;
}
我们可以使用
(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因此只需将结果四舍五入到适当的位数即可。这将比编写自己的近似值快得多,并且引入错误的机会更小。第二个sqrt函数不是sqrt函数,而是一个舍入函数。起初,这对我来说是非常误导的,直到我浏览了代码并意识到它根本没有试图计算sqrt!你可以考虑改变第二种方法的名称。我删除了整个函数,因为它在这里没有特定的值。。。
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);