Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 463
Daishisan Avatar asked Mar 12 '23 08:03

Daishisan


2 Answers

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.

like image 127
dimo414 Avatar answered Apr 30 '23 09:04

dimo414


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;
}
like image 36
Atilla Ozgur Avatar answered Apr 30 '23 09:04

Atilla Ozgur