Python Forum
Random data generation sum to 1 by rounding
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Random data generation sum to 1 by rounding
#1
Hello everyone,
I need a small help. I need to generate random values between 0 and 1. They must be successively ordered. Let me give you an example. Starting index is 3 and ending index 5, so in an array who has 10 index, they must be ordered like this:

A=[0 0 0.2 0.3 0.5 0  0 0 0 0]

Actually I do it in my code, I generate an array whose elements 0. Then I delete the part including the dtating and ending index and I insert to that part randomly generated value list (whose sum is equal to 1 for sure ). I generate these random values with the following code:

    def sum_to_x(n, x):
         values = [0.0, x] + list(np.random.uniform(low=0.0,high=x,size=n-1))
         values.sort()
         return [values[i+1] - values[i] for i in range(n)]
The problem my values are not rounded at all. I obtain something like that

Output:
[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.29047860679220283 0.002342106757806439 0.5462946648931827 0.16088462155680805]
How can I round them (two decimal for example) by keeping their sum to 1, still?

Thank you so much in advance
Yoriz write Oct-01-2021, 02:06 PM:
Please post all code, output and errors (in their entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply


Messages In This Thread
Random data generation sum to 1 by rounding - by juniorcoder - Oct-01-2021, 01:44 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  need help rounding joseph202020 7 1,520 Feb-21-2023, 08:13 PM
Last Post: joseph202020
  Node Flow Generation in Python Linenloid 0 724 Feb-21-2023, 07:09 PM
Last Post: Linenloid
  Allure Report Generation rotemz 0 893 Jan-24-2023, 08:30 PM
Last Post: rotemz
  from numpy array to csv - rounding SchroedingersLion 6 2,513 Nov-14-2022, 09:09 PM
Last Post: deanhystad
  Why doesnt chunk generation work? LotosProgramer 1 2,042 Apr-02-2022, 08:25 AM
Last Post: deanhystad
  Rounding issue kmll 1 1,541 Oct-08-2021, 10:35 AM
Last Post: Yoriz
Question PDF generation / edit SpongeB0B 2 2,183 Jul-28-2021, 05:59 AM
Last Post: SpongeB0B
  Not rounding to desired decimal places? pprod 2 2,673 Mar-05-2021, 11:11 AM
Last Post: pprod
  Calling Input for Random Generation ScaledCodingWarrior 1 1,962 Feb-02-2021, 07:27 PM
Last Post: bowlofred
  Decimal Rounding error project_science 4 2,917 Jan-06-2021, 03:14 PM
Last Post: project_science

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020