I have a list of floats that add up to an integer. For circumstantial reasons, I have to iterate using a for
loop x times, x being each float in the list, but since the argument for the range()
function must be an integer, each float must be rounded. However, I want the total number of loops to remain equal to the sum of the original floats, which doesn't usually add up to the sum of the rounded numbers. How would you solve this problem?
Thank you.
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
I recently had to solve a similar problem and decided it was something common enough to various projects of mine to generalize a python solution and package it. Check out
iteround
.Ok, this is going to be a bit mathematical:
You have a series of real numbers Xi Their sum equals N sum(Xi) = N
Let's break each real number to its floor integer and residual real part (between 0 and 1): Xi = Ri + fi
Now, you need a series of integers Yi that are as close to Xi, but are integers and also sum to N. We can break them like this: Yi = Ri + Fi (where Fi is an integer either 0 or 1).
Now we need that: sum(Yi) = sum(Xi) = N
If you break that, you'll get this equation as a requirement for the solution: sum(Fi) = sum(fi) = N - sum(Ri)
Let's denote: K = N - sum(Ri)
Now the solution is simple, choose the K elements which have the largest fi values, and assign their corresponding Fi to 1; assign the other Fi to 0.
Now you have your values for Yi which in your case are the loop sizes
Here's the code for it:
I think I don't have any bugs, I hope you get the idea even if so