Interesting Math Problem
Rüdiger Werner
larudwer at freenet.de
Thu Jun 5 15:25:28 EDT 2008
"BEES INC" <bees.inc at gmail.com> schrieb im Newsbeitrag
news:mailman.105.1212653740.1044.python-list at python.org...
...
Problem: Star Ratings
People can rate cheeseburgers on my website with a star rating of 0-5
stars (whole stars only), 5 being mighty tasty and 0 being disgusting.
I would like to show the average of everyone's ratings of a particular
cheeseburger to the nearest half star. I have already calculated the
average rating as a float (star_sum) and the total number of people
that rated the particular cheeseburger (num_raters). The result should
be stored as a float in a variable named "stars."
My Solution (in Python):
Well seems this is a typical half even rounding problem.
See
http://mail.python.org/pipermail/python-list/2008-April/485889.html
for a long discussion
However since your problem looks like a typical homework problem i made my
example
buggy by intention.
However the result should be correct.
have fun!
def myround(x):
d, m = divmod(x, 2)
return 2*d + round(m - 1) + 1
num = 1.5
for _i in xrange(30):
print num, ' -> ', myround(num * 2)/2
num -= 0.1
>pythonw -u "test18.py"
1.5 -> 1.5
1.4 -> 1.5
1.3 -> 1.5
1.2 -> 1.0
1.1 -> 1.0
1.0 -> 1.0
0.9 -> 1.0
0.8 -> 1.0
0.7 -> 0.5
0.6 -> 0.5
0.5 -> 0.5
0.4 -> 0.5
0.3 -> 0.5
0.2 -> 0.0
0.1 -> 0.0
-1.94289029309e-016 -> 0.0 < --- hint for bug
-0.1 -> 0.0
-0.2 -> 0.0
-0.3 -> -0.5
-0.4 -> -0.5
-0.5 -> -0.5
-0.6 -> -0.5
-0.7 -> -0.5
-0.8 -> -1.0
-0.9 -> -1.0
-1.0 -> -1.0
-1.1 -> -1.0
-1.2 -> -1.0
-1.3 -> -1.5
-1.4 -> -1.5
>Exit code: 0
to avoid the bug have a look at:
http://mail.python.org/pipermail/python-list/2008-April/485934.html
and try this example:
num = 3
for _i in xrange(num * 10,-num *10, -1):
if myround(float(_i)/10) != myround(num):
print num, " -> ", myround(num ), " --- ", myround(float(_i)/10)
print "-----"
num -= 0.1
More information about the Python-list
mailing list