JavaScript中的浮點運算精度能達到100%嗎?


浮點數

帶小數點的正數或負數整數稱為浮點數。例如,1.52、0.14和-98.345都是浮點數。而77、56、90和0則不是浮點數。

在JavaScript中,這種格式將數字儲存在64位中。分數儲存在第0到51位。指數儲存在第52到62位。符號位儲存在第63位。

浮點運算

JavaScript中的浮點運算永遠不可能達到100%的精確度。例如,分數1/6,即0.16666……,在某個點上會進行四捨五入。如果我們嘗試向上述值新增另一個小數值,我們可能無法得到預期的結果,因為兩個小數值相加時肯定會產生舍入誤差。這些舍入誤差通常很小,不會影響程式碼的輸出。

示例1

在下面的示例中,我們嘗試新增兩個小數值0.2和0.4。通常的輸出是0.6。但是,由於舍入誤差,期望的輸出與實際輸出不同。

<html> <head> <title>Rounding Errors</title> </head> <body> <h3 id=heading></h3> <h3>Thus, Floating point arithmetic will not show 100% accuracy in JavaScript.</h3> <script> let f_p_a = 0.2 + 0.4; document.getElementById("heading").innerHTML = "0.2 + 0.4 = " + f_p_a; </script> </body> </html>

示例2

下面的示例包含一個小數值和一個非小數值,分別為2.14和2。由於舍入誤差,實際輸出將與期望輸出不同。

<html> <head> <title>Rounding Errors</title> </head> <body> <h3 id=heading></h3> <h3>Thus, Floating point arithmetic will not show 100% accuracy in JavaScript.</h3> <script> let a = 2.14; let b = 2; let c = a + b; document.getElementById("heading").innerHTML = "2.14 + 2 = " + c; </script> </body> </html>

示例3

在下面的示例中,我們嘗試對一個小數值和一個非小數值進行求和。這個非小數值有16位,因為整數的精度最多到15位。這裡我們最終得到的輸出也包含舍入誤差

<html> <head> <title>Rounding Errors</title> </head> <body> <h4 id=heading></h4> <p>Integers will be accurate till they are upto 15 digits.</p> <p>Thus, Floating point arithmetic will not show 100% accuracy in JavaScript.</p> <script> var a = 2.14; var b = 9999999999999999; /*It will be 10000000000000000 (1e+16) at the time of execution */ var c = a + b; document.getElementById("heading").innerHTML = " 2.14 + 9999999999999999 = " + c; </script> </body> </html>

示例4

在下面的示例中,我們進行了兩個操作。第一個是舍入誤差,第二個是校正因子

要使用校正因子,我們需要用合適的10的冪進行乘法,以便在整數之間進行運算。

考慮下面的示例值0.1和0.2,校正因子為10。我們進行了校正。

<!DOCTYPE html> <html> <title>Online Javascript Editor</title> <head> <script> function test() { let a = 0.1; let b = 0.2; let c = a*b; document.write("Rounding error: "); document.write(c, "<br>"); let x = 10; let cf = (a * x) * (b * x) / (x * x); document.write("After using correction factor: "); document.write(cf); } test(); </script> </head> <body> </body> </html>

更新於:2022年9月19日

439次瀏覽

啟動您的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.