java - How can BigDecimal make no floating point inaccuracy? -


i have known there floating point inaccuracy regardless of os, programming language. i, however, found there no inaccuracy in example. how can possible? think converting stirng double needed calculation, there should floating point inaccuracy!

import java.math.*;  class noerrorbigdecimal {     public static void main(string[] args)     {         bigdecimal e1=new bigdecimal("1.6");         bigdecimal e2=new bigdecimal("0.1");           system.out.println("result of add : "+e1.add(e2));         system.out.println("result of multiplication : "+e1.multiply(e2));     } } 

how can bigdecimal make no floating point inaccuracy?

the answer cannot.

floating point inaccuracy (as call it) fundamental of practical number representations used in computers.

the counter example proposition bigdecimal value of 1 / 3 cannot represented precisely using single bigdecimal (or float or double matter).

  • it representable precisely using base-3 floating point representation, impractical.

  • it representable precisely (hypothetical) arbitrary precision rational number representation, there no standard java se class implements that.

another counter-example pi (3.14159...). since irrational, not have finite numeric representation (except in impractical sense involves circular logic ...)


on other hand, if confine numbers can represent precisely finite decimal floating-point strings (like "1.6" , "0.1"), bigdecimal can represent of numbers ... precisely.

i think converting stirng double needed calculation, there should floating point inaccuracy!

actually, doesn't follow there inaccuracy. depends on specific calculation, specific representation, , (often) actual values. example:

  • i can (trivially) implement calculation 1 / 2 , (provided hardware works) guarantee the result represented accurately float or double.

  • the conversion of decimal number in string form bigdecimal not involve calculation has risk of loss of accuracy. (as implemented standard libraries, , assuming there o(n) available memory ... n input string length.)


Comments

Popular posts from this blog

java - Andrioid studio start fail: Fatal error initializing 'null' -

android - Gradle sync Error:Configuration with name 'default' not found -

StringGrid issue in Delphi XE8 firemonkey mobile app -