When should I use the "strictfp" keyword in java?
Asked Answered
N

11

284

I've looked up what this does, but does anyone actually have an example of when you would use the strictfp keyword in Java? Has anyone actually found a use for this?

Would there be any side-effects of just putting it on all my floating point operations?

Narcose answered 5/2, 2009 at 21:8 Comment(5)
Always, unless you actually need the performance more than you need reproducibility.Except
@Except - or the precision/correctness. x86/x64, for example, use 80-bit floating point registers internally, so the result will be more accurate for a long calculation without strictfp.Period
@Robert Actually, the spec guarantees limited precision of the mantissa. The only difference is that it may use a larger exponent precision than normal, which has differences in rare cases due to double rounding.Except
I'm thinking that in addition to the option of sprinkling this useful modifier all around the joint, new sfloat & sdouble primitive strictfp datatypes might be a good idea.Filariasis
You will need to use never in the production code unless you are writing a scientific calculator.Inquiry
M
295

Strictfp ensures that you get exactly the same results from your floating point calculations on every platform. If you don't use strictfp, the JVM implementation is free to use extra precision where available.

From the JLS:

Within an FP-strict expression, all intermediate values must be elements of the float value set or the double value set, implying that the results of all FP-strict expressions must be those predicted by IEEE 754 arithmetic on operands represented using single and double formats. Within an expression that is not FP-strict, some leeway is granted for an implementation to use an extended exponent range to represent intermediate results; the net effect, roughly speaking, is that a calculation might produce "the correct answer" in situations where exclusive use of the float value set or double value set might result in overflow or underflow.

In other words, it's about making sure that Write-Once-Run-Anywhere actually means Write-Once-Get-Equally-Wrong-Results-Everywhere.

With strictfp your results are portable, without it they are more likely to be accurate.

Motor answered 5/2, 2009 at 21:23 Comment(8)
Use it for reproducible scientific results and bit-exact unit tests.Naphtha
"If you don't use strictfp, the JVM implementation is free to use extra precision where available"--you make that sound like a bad thing :PJarl
@LinkTheProgrammer it certainly can be a bad thingFamiliarity
@TimCastelijns I suppose Happy Wheels is your reference? The replays record keystrokes; due to FP-math implementation precision diversity, the replays are only accurate on similar hardware. Can you name a more realistic problem caused by floating point math variability? I can imagine perhaps a particle simulator, but what else?Jarl
So this means we should always use strictfp in production where multiple platforms involved?Alby
What exactly does "intermediate results" in this context mean? Changes to the float before it gets passed/returned? Individual steps of a multistep float operation?Oneal
Also note that of Java 17, floating point operations are always strict again and strictfp is not required anymore. Actually, the compiler will issue warnings when it's used.Gash
@Gash so basically, after Java 17, the strictfp keyword is meaningless.Sternutation
I
70

Actually, there's a good Wikipedia article about strictfp, with a link to the Java specification's section on Floating-Point Types, Formats, and Values.

Reading between the lines, the implication is that if you don't specify strictfp, then the JVM and JIT compiler have license to compute your floating-point calculations however they want. In the interest of speed, they will most likely delegate the computation to your processor. With strictfp on, the computations have to conform to IEEE 754 arithmetic standards, which, in practice, probably means that the JVM will do the computation.

So why would you want to use strictfp? One scenario I can see is in a distributed application (or multiplayer game) where all floating-point calculations need to be deterministic no matter what the underlying hardware or CPU is. What's the trade-off? Most likely execution time.

Impressible answered 5/2, 2009 at 21:16 Comment(3)
“an extended exponent range to represent intermediate results” is not “license to compute your floating-point calculations however they want”, and in practice, even strictfp computations make use of even an unhelpful 8087 FPU. It is only the case that a bit of care is required then. See #18497060Margarettemargarida
I agree with @PascalCuoq re: "license to compute your floating-point calculations however they want". If anything, the opposite seems to be true in this case, since strictfp assures compliance with the IEEE 754 standard (so that you get the same result on all platforms). The only drawback I can see is that you might lose the benefits of having a really good FPU available in your native hardware.Nonlinearity
In short words, use the strictfp, when you need the same floating calculation each time on different CPU model. Note that this can be overkill if your floating number is not that big.Mclain
L
34

Java 17 Update

strictfp had such a narrow set of use cases that as of Java 17, its functionality has been removed. It is still a valid modifier but now strictfp does nothing (JLS source).

Instead, all floating-point operations are now strict, as was the case before strictfp was introduced in Java 1.2. On modern processors there is no longer any extra performance cost.


Original answer

Here are several references:

  • Using strictfp (JDC Tech Tip)

  • jGuru: What is the strictfp modifier for? When would I consider using it?

    Basically, what it all boils down to is whether or not you care that the results of floating-point expressions in your code are fast or predictable. For example, if you need the answers that your code comes up with which uses floating-point values to be consistent across multiple platforms then use strictfp.

  • strictfp - Java Glossary

    Floating point hardware calculates with more precision, and with a greater range of values than the Java specification requires. It would be confusing if some platforms gave more precision than others. When you use the strictfp modifier on a method or class, the compiler generates code that adheres strictly to the Java spec for identical results on all platforms. Without strictfp, is it is slightly laxer, but not so lax as to use the guard bits in the Pentium to give 80 bits of precision.

  • And finally the actual Java Language Specification, §15.4 FP-strict Expressions:

    Within an FP-strict expression, all intermediate values must be elements of the float value set or the double value set, implying that the results of all FP-strict expressions must be those predicted by IEEE 754 arithmetic on operands represented using single and double formats. Within an expression that is not FP-strict, some leeway is granted for an implementation to use an extended exponent range to represent intermediate results; the net effect, roughly speaking, is that a calculation might produce "the correct answer" in situations where exclusive use of the float value set or double value set might result in overflow or underflow.

I've never personally had a use for it, though.

Laboured answered 5/2, 2009 at 21:24 Comment(2)
You wrote: I've never personally had a use for it, though. I am exactly the same. Does anyone have a Real World example where it was used?Seavey
@Seavey You have been very fortunate. Yes. Reconciliation with a mainframe. The books didn't quite balance without strictfp. That was an interesting bug to find and fix.Safir
I
29

It all began with a story,

When java was being developed by James Gosling, Herbert and rest of his team. They had this crazy thing in mind called platform independency. They wanted to make oak(Java) so much better that it would run exactly same on any machine having different instruction set, even running different operating systems. But, there was a problem with decimal point numbers also known as floating point and double in programming languages. Some machines were built targeting efficiency while rest were targeting accuracy. So, the later(more accurate) machines had size of floating point as 80 bits while the former(more efficient/faster) machines had 64 bit doubles. But, this was against there core idea of building a platform independent language. Also, this might lead to loss of precision/data when a code is built on some machine(having double of 64 bit size) and run on another kind of machine(having double of 80 bit size).

Up-Sizing can be tolerated but Down-Sizing can't be. So, they came across a concept of strictfp i.e. strict floating point. If you use this keyword with a class/function then its floating point and doubles have a consistent size over any machine. i.e. 32/64 -bit respectively.

Instant answered 13/7, 2015 at 21:44 Comment(4)
strictfp was introduced in Java 1.2. This was much later than when oak was designed.Kava
"decimal point numbers also known as floating point" -- Decimal means base 10, and has nothing to do with floating point representations.Congruent
@Congruent Here in America (I don't know about other English-speaking nations) the period that separate the whole and fractional components of a number is called Decimal Point. That's what abhimanyuaryan meant. I'm sure you understood. There is no reason to get caught in semantics (in this case).Sternutation
english.stackexchange.com/questions/422162/…Congruent
C
12

As the other answers mentioned it cause the intermediate floating point results to conform to the IEEE specification. In particular x86 processors can store intermediate results with different precision from the IEEE spec. The situation gets more complicated when the JIT optimizes a particular computation; the order the instructions could be different each time resulting in slightly different rounding.

The overhead incurred by strictfp likely to be very processor and JIT dependent. This wikipedia article on SSE2 seems to have some insight into the problem. So if the JIT can generate SSE instructions to perform a calculation it seems that strictfp will not have any overhead.

In my current project there are a few places where I use strictfp. There is a point where potential cosmic rays need to be removed from pixel values. If some outside researcher has the the same pixel value and cosmic ray in front them they should get the same resulting value as our software.

Corbel answered 5/2, 2009 at 21:45 Comment(0)
H
8
  • strictfp is a modifier which restricts floating point calculations as per IEEE 754.

  • This can be used on whole class like "public strictfp class StrictFpModifierExample{}" or on method "public strictfp void example()".If it is used on class than all methods will follow IEEE 754 and if used on method then particular method will follow IEEE 754.

  • Why it is used??::: As different platforms have different floating point hardware which calculates with more precision and greater range of values than the java specification requires which may produce diffrent output on diffrent plateforms.so it confirms the same output irrespective of diffrent plateforms

  • strictfp also ensures to take advantage of the speed and precision of the extended precision floating-point operations.

  • There is no disadvantage with this keyword we can use when we are doing floating point calculations

  • My last point is --What is IEEE754 in short IEEE 754 defines standard method for both floating point calculations and storage of floating point values in either single (32-bit, used in Java floats) or double (64-bit, used in Java doubles) precision.It also defines norms for intermediate calculations and for extended precision formats.

Hubris answered 19/9, 2012 at 19:9 Comment(0)
P
3

As of Java 17+, the strictfp modifier is obsolete and does nothing. You should no longer use this modifier.

Pyromancy answered 31/12, 2021 at 23:39 Comment(0)
F
2

strictfp is a keyword and can be used as a non Non-access modifier for classes or a methods (but never variables). Marking a class as strictfp means that any method code in the class will conform to the IEEE 754 standard rules for floating points.

Without that modifier, floating points used in the methods might behave in a platform-dependent way. With it you can predict how your floating points will behave regardless of the underlying platform the JVM is running on. The downside is that if the underlying platform is capable of supporting greater precision, a strictfp method won't be able to take advantage of it.

If you don't declare a class as strictfp, you can still get strictfp behavior on a method-by-method basis, by declaring a method as strictfp.

~ SCJP Sun®Certified Programmer for Java™ 6 - Kathy Sierra & Bert Bates ~

Flavio answered 8/7, 2015 at 11:17 Comment(0)
S
1

The one (and only time) I needed this was reconciliation with an IBM ZSeries. Outside of accounting and mainframes; no. It has been sometime, but I am fairly certain mainframes haven't changed.

Safir answered 18/2, 2022 at 23:55 Comment(0)
V
0

May below example help in understanding this more clear : In java whenever we are using looking for precise information for any operation e.g. if we do double num1 = 10e+102; double num2 = 8e+10 ; result = num1+ num2;

        The output will be so long and not precise, becasue it is precissed by the hardware e.g JVM and JIT has the license 
        as long as we dont have specify it Strictfp

Marking it Strictfp will make the result Uniform on every hardware and platform, because its precised value will be same
One scenario I can see is in a distributed application (or multiplayer game) where all floating-point calculations need to 
be deterministic no matter what the underlying hardware or CPU is.
Vernellvernen answered 18/8, 2018 at 7:54 Comment(0)
G
0

'strictfp' keyword is used to force the precision of floating point calculations (float or double) in Java conform to IEEE’s 754 standard, explicitly. If you do not use strictfp keyword, the floating point precision depends on target platform’s hardware.

If an interface or class is declared with strictfp, then all methods and nested types within that interface or class are implicitly strictfp.

Reference link

Germainegerman answered 23/12, 2019 at 13:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.