1

I want to make a list of floats of N length whose total sum is always 1 and each float is incremented by d amount.

For example, let N = 4 and d = 0.01:

The desired outcome would be like so:

[0.90, 0.02, 0.03, 0.05]
[0.89, 0.02, 0.03, 0.06]
....
# And continues until all possible sums of 1 with the above settings is reached.
# An individual value CAN NOT = 0

I'm trying to think of some logic for this but I need some help. Previously I had asked a question of similar nature, but uses random numbers instead of all possible combinations.

Community
  • 1
  • 1
Alex McLean
  • 2,524
  • 5
  • 30
  • 53

1 Answers1

2

I think itertools makes this pretty easy:

from itertools import permutations, ifilter

N = 4
d = 0.01
D = int(1/d)   


perms = ifilter(lambda x: sum(x) < D, permutations(range(1,D-1), N-1))
tuples = []
for i in perms:
    tuples.append(i + (D-sum(i),))

mylist = [ [ i*d for i in eachtuple ] for eachtuple in tuples ]

print mylist

I had assumed that d will be 10^(-n) for some integer n, but this would work for anything with an integer reciprocal (0.05 and 0.2 should work, but not 0.03).

Floats being floats, you get some floating-point errors, which you could control with an appropriate round inside that nested list comprehension.

kmacinnis
  • 608
  • 5
  • 8