Daishisan
Daishisan

Reputation: 290

Does Java's BigDecimal leverage the hardware architecture like long double in C++?

As I understand it, long double in C++ actually leverages the hardware architecture (at least for some architectures). Does BigDecimal in Java do this for small enough inputs?

Upvotes: 4

Views: 451

Answers (3)

Patricia Shanahan
Patricia Shanahan

Reputation: 26185

The most important difference between BigDecimal and typical hardware long double support is the floating point radix.

The value of a BigDecimal is an integer multiplied by a power of ten. Floating point hardware is typically based on IEEE binary floating point, and each value is an integer multiplied by a power of two.

Some calculations whose inputs are exactly representable in long double have results that incur greater rounding error in long double than in BigDecimal with a given scale. For example, 1 and 10 can both be represented exactly in both formats. The result of dividing 1 by 10 can be represented exactly in BigDecimal with scale at least 1, but not in any radix 2 format.

There are, of course, many rationals that cannot be represented exactly in either format. Consider 1/3. Even there, BigDecimal will get greater or lesser rounding error, depending on scale. The answer is unlikely to be exactly the same in long double and BigDecimal.

Doing tests on each calculation to determine whether the two formats get the same answer would destroy any performance gain from using hardware assist.

Upvotes: 2

dimo414
dimo414

Reputation: 48864

Does BigDecimal in Java do this for small enough inputs?

No, and it could not. Floating-point numbers are lossy, while every BigDecimal has an associated precision, and can represent exactly any number below that precision. There is no "small enough input" that can usefully be rendered as a floating point number, because even if you happen to have a BigDecimal value that can be represented exactly in floating-point notation, you'd be hard-pressed to do any sort of operations on that value and maintain the specified precision.

Put another way, the purpose of BigDecimal is to offer precision while sacrificing speed. That runs exactly contrary to floating-point, which sacrifices precision in favor of speed.


It sounds like you're asking if Java offers a way to work with long double sized floating-point numbers, and there is not. We can conclude from the fact that it's not provided that the JDK authors have never felt it was necessary to add to the language.

Upvotes: 5

Atilla Ozgur
Atilla Ozgur

Reputation: 14721

No. BigDecimal does not leverage any hardware architecture. See for example a constructor of BigDecimal from Java Source Code.

BigDecimal(BigInteger intVal, long val, int scale, int prec) {
    this.scale = scale;
    this.precision = prec;
    this.intCompact = val;
    this.intVal = intVal;
}

Upvotes: 1

Related Questions