Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
834 views
in Technique[技术] by (71.8m points)

rounding up the python list values before saving to DB

I'm saving the monthly forecasted values in postgesDB matching with actual result using python eg monthly forecasted values [10.5, 20.6, 30.8, 5.4, 0, 1, 1.4, 2.2] which sums 71.9 and actual result 65

my solution is to get a rescale factor by dividing actual to forecasted sum 65 / 71.9 = 0.904 and multiply that to all values in forecasted values now new list will be [9.492, 18.622, 27.843, 4.881, 0, 0.904, 1.265, 1.988] which sums to 64.995 and rounded to 65 the actual value, but now I was asked to forecasted values can only be integers, what is the best way to refactor the list to have the forecasted values as only "positive integers" and be close to actual result by +-1. I tried rounding the list values after refactor but for list large records the difference to actual value is more that 100


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
results = []
forecast = [10.5, 20.6, 30.8, 5.4, 0, 1, 1.4, 2.2]
actual_result = 65
rounded_list = [round(number) for number in forecast if number >= 0]

percentage = actual_result / sum(rounded_list)

for number in rounded_list:
     results.append(number * percentage)

Print list:

[9.154929577464788, 19.225352112676056, 28.380281690140844, 4.577464788732394, 0.0, 0.9154929577464789, 0.9154929577464789, 1.8309859154929577]

Print sum list:

65.0

If you want to be very precise and the forecast list should only be integer:

results = []
forecast = [10.5, 20.6, 30.8, 5.4, 0, 1, 1.4, 2.2]
actual_result = 65
rounded_list = [number * 10 for number in forecast if number >= 0]

percentage = 65 * 10 / sum(rounded_list)

for number in rounded_list:
    results.append(number * percentage / 10)

Print list:

[9.492350486787204, 18.6230876216968, 27.8442280945758, 4.881780250347704, 0.0, 0.9040333796940194, 1.265646731571627, 1.9888734353268425]

Print list sum:

65.0

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...