0

Basically I am changing layout ratios. I have to change current layout ratio to another ratio. There is a code snippet I am using in my application.

import java.util.*;
public class Big{


public static void main(String args[]){
float b=(new Scanner(System.in)).nextFloat();
float a=(b*((float)225/440));

//Another layout ratio height
System.out.println(a);

//Back to previous layout height
float c=(a*((float)440/225));
System.out.println(c);



}

}

Below are some input and their respected outputs:

On input value- 50,60.0,65 and 69.9999, Code is returning same outputs-50,60.0,65 and 69.9999 respectively. But when I am trying to put 70 and 80, Code is returning approximate values as 69.99999 and 79.99999 respectively. The question is- Why am I getting these approximate value not exact values in case of 70 and 80. There can be some other cases. I am trying to get exact values in all the cases.

Rupesh Kumar
  • 41
  • 1
  • 8
  • 1
    Read this [article](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) as well. In the future, make a bit more effort to search for an answer both here and in general before posting a new question. The "brokenness" of floating point math in computing is a common topic of discussion. – MarsAtomic Aug 23 '20 at 20:29

1 Answers1

-1

Use BigDecimal for exact calculations, although be careful because is REALLY slow.

As the comments on top say, floating type math is unexact by design: there is no way to represent the infinity of numbers that can be created in the set of real numbers

BigDecimal exists for these kind of calculations. But it trades preciseness for speed.

JoshiRaez
  • 97
  • 9
  • `BigDecimal` will not eliminate rounding problems. The code in the question divides by 440, for which the real-number result cannot be represented unless there is a factor of 11 in the numerator, and by 225, which calls for a factor of 9. – Eric Postpischil Aug 23 '20 at 20:59
  • @ericpostpischil how can I solve? – Rupesh Kumar Aug 23 '20 at 21:10
  • @JoshiRaez thanks for the approach I tried but not working. Can you tell me where can I implement big decimal to solve this problem? – Rupesh Kumar Aug 23 '20 at 21:13
  • @RupeshKumar Don't ask new questions in comments. Stack Overflow uses a Q&A format -- this is not a discussion forum. Post a new question as a question. If you do so, trust me, you will get answers. – MarsAtomic Aug 23 '20 at 22:50
  • @RupeshKumar: You do not implement `BigDecimal`; you use it. But you would not use it for this problem. It is not clear you have a problem. Most uses of floating-point arithmetic expect it to produce results different from real-number arithmetic, because floating-point arithmetic is designed to only approximate real-number arithmetic. Why do you need exact results? What “layout” are you working with? Enter a question with complete details about the actual problem. – Eric Postpischil Aug 23 '20 at 23:10