Floating Point Rounding
January 8, 2013
This is easy enough:
(define (round f n)
(/ (truncate (+ (* f (expt 10 n)) 0.5)) (expt 10 n)))
The expression (expt 10 n)
returns 1000 when n is 3, 100 when n is 2, 1 when n is 0, and 1/10 when n is -1. This number is first multiplied by f and then divided into the result, so the output has the same order as the input. In between the multiplication and the division, 0.5 is added, then the result of the addition is truncated, which has the desired rounding effect. There is no need for extra credit here; the function works perfectly well for both positive and negative n.
You can run the program at http://programmingpraxis.codepad.org/AF35jtp1.
My Java solution here.
a C solution
a Scheme solution
I guess I should check the suggested solution to see if it is essentially the same as mine before posting mine. ^_^
[…] Pages: 1 2 […]
> javabloggi said
>January 8, 2013 at 10:52 AM
>
>My Java solution here.
Your solution does not perform rounding correctly. You seem to be checking the digit in one more significant place value than you need to be in order to determine if rounding up is needed.
For example, from your output:
01 Enter numbers:
02 1000/7,3
03 Answer: 142.858
However, the correct answer should be 12.857.
Here’s my java solution:
public class FPR {
public static double round(double f, int n) {
double div = Math.pow(10, (double) n);
if (div*f*10 % 10 >= 5) {
return ((double) ((int) (div*f)) + 1)/div;
} else {
return ((double) ((int) (div*f)))/div;
}
}
public static void main(String[] args) {
for (int i = 3; i >= -2; i–) {
System.out.println(“1000/7,” + i + “: ” + round(1000.0/7.0, i));
}
}
}
Thanks.
Katzby
>However, the correct answer should be 12.857.
Sorry, I meant to say it should be 142.857.
Thanks.
Katzby
An overly complicated python version =)
>However, the correct answer should be 12.857.
>Sorry, I meant to say it should be 142.857.
>Thanks.
>Katzby
Thanks for letting me know. I corrected the mistake.
Every answer posted so far handles negative values incorrectly. Also, it doesn’t appear anyone implemented an unbiased tie-breaking scheme?
This solution handles both issues correctly (tie-breaking done with round-to-even) as well as the extra credit.
However, it doesn’t support the technical definition of significant digits.
oops typo on line 11. should be: