Operation order giving different results | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

Operation order giving different results

When solving the shape challenge in Java, I couldn't figure out why my code was not passing test case number 3 (locked). Turns out the problem was that for my calculation of the area of the circle I was using width*width*Math.PI instead of Math.PI*width*width. Changing the order fixed the problem. But why?! As far as I understand, the order of factors shouldn't change the result of a multiplication. Is this some kind of expected behavior with Math.PI, or some kind of bug? https://code.sololearn.com/cva0my76wT1A/?ref=app

30th Aug 2021, 3:22 PM
Leandro
Leandro - avatar
4 Answers
+ 4
i checked the output in java for 3 different sequences of the multiplication like done by Leandro, and the result was all the same. but 1 of my 5 trials was timed out, so may be it is an issue of the server. But in general the sequence of operands with a multiplication does not affect the result.
30th Aug 2021, 4:49 PM
Lothar
Lothar - avatar
+ 4
Can you save your code on SL Playground and link here for posibility to help.
30th Aug 2021, 3:58 PM
JaScript
JaScript - avatar
+ 2
Edited with the code that caused the error and the challenge description. I'm pretty sure Lothar is correct, it must have been a time out issue. Thank you all very much!
31st Aug 2021, 3:10 AM
Leandro
Leandro - avatar
+ 1
I‘m not sure yet but we are in digital world. That means there can be a difference when the operation at the beginning convert integer to double or at the last multiplication. Maby calculating on PC with another compiler can be answer this.
31st Aug 2021, 7:17 AM
JaScript
JaScript - avatar