Java 17 Recipes


-7. Restore Always-Strict Floating-Point Semantics


Download 3.2 Mb.
Pdf ko'rish
bet37/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   33   34   35   36   37   38   39   40   ...   245
Bog'liq
Java 17 Recipes

2-7. Restore Always-Strict Floating-Point Semantics
 Problem
You want to ensure the same precision and result on every platform for floating points.
 Solution
Java 17 restores the default always-strict function, making the floating-point operations 
uniformly strict. So, you can ensure platform-independent floating-point computations; 
for example, the following is the old version.
strictfp class AppliedClass{}//strict floating point applied on class
strictfp interface AppliedInterface{}// strict floating point applied on 
interface
And simply, the new version is as follows.
class AppliedClass{}//strictfp applied on class
interface AppliedInterface{}//strictfp applied on interface
The following is an example.
public strictfp class SumFPnumbersStrict {
public double sumNumbers(double fpOne, double fpTwo) {
return fpOne + fpTwo;
}
It becomes the following.
public class sumFPnumbers {
public double SumNumbers(double fpOne, double fpTwo) {
return fpOne + fpTwo;
}
The following is an example of the main class.
public class Main {
public static void main (String[] args) {
SumFPnumbers sn = new SumFPnumbers ();
System.out.println("SUM : "+sn.sumNumbers(1.2,3.4));
Chapter 2 enhanCements from Java 9 through Java 17 


60
SumFPnumbersStrict sns = new SumFPnumbersStrict();
System.out.println("SUM : "+sns.sumNumbers(1.2,3.4));
}
}
 How It Works
Since Java 17, floating-point computations were platform-dependent (i.e., depends 
on the hardware). This enhancement helps avoid strictfp behavior and not make all 
floating-point operations uniformly strict. Existing Java code using strictfp could be used 
without the modifier.
For more information on floating points, see the documentation at 
https://
openjdk.java.net/jeps/306
.

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   33   34   35   36   37   38   39   40   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling