For the following code (Java):
double d = (double) m / n; //m and n are integers, n>0
int i = (int) (d * n);
i == m
Is the last expression always true?
If it’s not is this always true?:
i = (int) Math.round(d * n);
i == m
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The second question you ask concerns how large an ulp is in Java.
If the ulp exceeds
1/(n), then rounding the multiplication would not recover the original divided int. Typically, larger ulps are associated with larger double values. An ulp associated with a double starts to exceed 1 at around 9E15; if your recovered doubles were around there, then you might finding problems with round() not getting the expected answer. As you are working with int values, though, the largest value of the numerator of your division will beInteger.MAX_VALUE.The following program tests all the positive integer values of
nto see which one causes the largest potential for rounding error when trying to recover the divided int:The output is:
Rounding that using Math.round, then casting to int should recover the original int.