0
System.out.println((int) (368*Math.pow(2416,2)+100*2416+100));

does not produce the same output as a calculator would or python, what might be the reason for this?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • 6
    What are you getting? What are you expecting? Why are you casting to an integer? – OneCricketeer Sep 17 '21 at 13:41
  • 3
    what is the result you are having, and what is the result you expect ? – Judy1989 Sep 17 '21 at 13:42
  • Does this answer your question? [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Olaf Kock Sep 17 '21 at 13:44
  • 3
    One thing new programmers stumble over is how incredibly dumb computers are. They always do exactly what we tell them, even if that doesn't make *any* sense. Here, we've asked the computer to perform a calculation that we (should) know is going to be pretty large, and store the result in a data structure that can't hold the result. So, you get a broken answer. Contrary to intuitive sense, computers aren't good at math; programmers are. So you, the programmer, are responsible for making sure the computer can perform the requested calculation (which it cant) – Gus Sep 17 '21 at 13:51
  • 2
    It's not the duplicate that I linked initially. But following Gus' suggestion: Look at Integer.MAX_VALUE and compare your result (before casting to int) and also cast to long. Check Long.MAX_VALUE as well. Most likely a duplicate to a different question - would have been obvious if you'd given the values from the start. – Olaf Kock Sep 17 '21 at 13:54

1 Answers1

0

The result of the expression is larger than the range of java int. Since you are casting to int (java primitive type) which ranges from -2,147,483,648 (-2^31) to 2,147,483,647 ((2^31)-1), the code produces 2147483647(upper limit of java int data-type) as the output whereas the calculator will give correct result.

vinayak
  • 1
  • 2