strictfp
Strictfp —— Java 關鍵字。
strictfp, 即 strict float point (精確浮點)。
strictfp 關鍵字可應用於類、接口或方法。使用 strictfp 關鍵字聲明一個方法時,該方法中所有的float和double表達式都嚴格遵守FP-strict的限制,符合IEEE-754規范。當對一個類或接口使用 strictfp 關鍵字時,該類中的所有代碼,包括嵌套類型中的初始設定值和代碼,都將嚴格地進行計算。嚴格約束意味著所有表達式的結果都必須是 IEEE 754 算法對操作數預期的結果,以單精度和雙精度格式表示。
如果你想讓你的浮點運算更加精確,而且不會因為不同的硬件平臺所執行的結果不一致的話,可以用關鍵字strictfp.
示例 1
下面的示例演示瞭一個使用 strictfp 修飾符聲明的類。
// Example of precision control with strictfp
public strictfp class MyClass
{
public MyClass(){}
public static void main(String[] args)
{
float aFloat = 0.6710339f;
double aDouble = 0.04150553411984792d;
double sum = aFloat + aDouble;
float quotient = (float)(aFloat / aDouble);
System.out.println("float: " + aFloat);
System.out.println("double: " + aDouble);
System.out.println("sum: " + sum);
System.out.println("quotient: " + quotient);
}
}
示例輸出
float: 0.6710339
double: 0.04150553411984792
sum: 0.71253945297742238
quotient: 16.1673355
示例 2
下面的示例演示瞭一個使用 strictfp 修飾符聲明的方法。
// Example of precision control with strictfp:
public class MyClass2
{
public float aFloat;
public double aDouble;
public MyClass2(){}
public strictfp double add(float a, double b)
{
return (a + b);
}
public static void main(String[] args)
{
MyClass2 myClass2 = new MyClass2();
myClass2.aFloat = 0.6710339f;
myClass2.aDouble = 0.04150553411984792d;
double sum = myClass2.add(myClass2.aFloat, myClass2.aDouble);
System.out.println("float: " + myClass2.aFloat);
System.out.println("double: " + myClass2.aDouble);
System.out.println("sum: " + sum);
}
}
示例輸出
float: 0.6710339
double: 0.04150553411984792
sum: 0.71253945297742238
==============================================================
自Java2以來,Java語言增加瞭一個關鍵字strictfp。strictfp的意思是FP-strict,也就是說精確浮點的意思。在Java虛擬機進行浮點運算時,如果沒有指定strictfp關鍵字時,Java的編譯器以及運行環境在對浮點運算的表達式是采取一種近似於我行我素的行為來完成這些操作,以致於得到的結果往往無法令你滿意。而一旦使用瞭strictfp來聲明一個類、接口或者方法時,那麼所聲明的范圍內Java的編譯器以及運行環境會完全依照浮點規范IEEE-754來執行。因此如果你想讓你的浮點運算更加精確,而且不會因為不同的硬件平臺所執行的結果不一致的話,那就請用關鍵字strictfp。
你可以將一個類、接口以及方法聲明為strictfp,但是不允許對接口中的方法以及構造函數聲明strictfp關鍵字,例如下面的代碼:
1. 合法的使用關鍵字strictfp
strictfp interface A {}
public strictfp class FpDemo1 {
strictfp void f() {}
}
2. 錯誤的使用方法
interface A {
strictfp void f();
}
public class FpDemo2 {
strictfp FpDemo2() {}
}
一旦使用瞭關鍵字strictfp來聲明某個類、接口或者方法時,那麼在這個關鍵字所聲明的范圍內所有浮點運算都是精確的,符合IEEE-754規范的。例如一個類被聲明為strictfp,那麼該類中所有的方法都是strictfp的。
作者:zongquanliu