'decomposing a floating-point number into numbers from a list
Given a floating-point number f=0.0...0.999 and a list k=[0.500, 0.333, 0.250, 0.200, 0.166, 0.143, 0.125, 0.111, 0.100, 0.091]. It is necessary to decompose the number f into the numbers from the list k. If there is no exact match, then you need to subtract from the number f in increments of 0.001 until the initial condition is met. that is, f >= sum ki. My code does not work for all cases. How to solve the problem?
import itertools
def func(n,l):
return [a for i in [itertools.product(l,repeat=x) for x in range(1,20)] for a in i if sum(a) == n]
float_num=0.176
k=[0.500, 0.333, 0.250, 0.200, 0.166, 0.143, 0.125, 0.111, 0.100, 0.091]
decomp=func(float_num, k)
print('decompose of', float_num, ':')
if decomp == []:
while decomp == []:
float_num = float_num - 0.001
decomp=func(float_num, k)
if float_num == 0.091:
decomp=func(float_num, k)
break
elif float_num < 0.091:
decomp=[0]
break
print(decomp)
Solution 1:[1]
This code should give you the closest you can get to the target:
target=0.8
mini=1000
for i in range(0, len(k)+1):
for selection in itertools.combinations(k, i):
m=sum(selection)
if np.abs(target-m)<mini:
mini=np.abs(target-m)
print (selection, m)
I guess, you can take it from here:)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kilian |
