How to get N random integer numbers whose sum is equal to M

2024/9/20 13:37:36

I want to make a list of N random INTEGER numbers whose sum is equal to M number.

I have used numpy and dirichlet function in Python, but this generate double random number array, I would like to generate integer random number.

import numpy as np 
np.random.dirichlet(np.ones(n))*m

The solution can use other distribution the sense is resolve the problem.

Answer

The problem with using dirichlet for this is that it is a distribution over real numbers. It will yield a vector of numbers in the range (0,1), which sum to 1, but truncating or rounding them may remove the guarantee of a specific sum. Following this post we can get the desired effect from the multinomial distribution (using np.random.multinomial), as follows:

from numpy.random import multinomialnp.random.multinomial(m, np.ones(n)/n)

This will generate n integers between 0 and m, whose sum is m, with equal probability of drawing a given position. The easiest way to visualize this is to consider the result as describing a set of draws from a fixed set of objects (e.g., die rolls drawing from the integers from 1 to 6) where the final array is the number of times the corresponding object was drawn. The total will always sum to the given number of total draws (rolls).

https://en.xdnf.cn/q/72494.html

Related Q&A

Why sqlalchemy declarative base object has no attribute query?

I created declarative table. from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, String from sqlalchemy.dialects.postgresql import UUID import uuidBase = declarative_…

Django ModelForm not saving data

Ive tried solutions from the following posts: Saving data from ModelForm : Didnt workModelForm data not saving django : Didnt work. Im trying to save data from a ModelForm into the model. models.py:cla…

When is it appropriate to use sample_weights in keras?

According to this question, I learnt that class_weight in keras is applying a weighted loss during training, and sample_weight is doing something sample-wise if I dont have equal confidence in all the …

Django South - turning a null=True field into a null=False field

My question is, what is the best practice for turning a null=True field into a null=False field using Django South. Specifically, Im working with a ForeignKey.

Apostrophes are printing out as \x80\x99

import requests from bs4 import BeautifulSoup import resource_url = requests.get(http://www.nytimes.com/pages/business/index.html) div_classes = {class :[ledeStory , story]} title_tags = [h2,h3,h4,h5,h…

Have Sphinx replace docstring text

I am documenting code in Sphinx that resembles this: class ParentClass(object):def __init__(self):passdef generic_fun(self):"""Call this function using /run/ParentClass/generic_fun()&quo…

exit is not a keyword in Python, but no error occurs while using it

I learn that exit is not a keyword in Python by,import keyword print(exit in keyword.kwlist) # Output: FalseBut there is no reminder of NameError: name exit is not defined while using it. The outpu…

Tensorflow Datasets Reshape Images

I want to build a data pipeline using tensorflow dataset. Because each data has different shapes, I cant build a data pipeline.import tensorflow_datasets as tfds import tensorflow as tfdataset_builder …

Why is the python client not receiving SSE events?

I am have a python client listening to SSE events from a server with node.js APIThe flow is I sent an event to the node.js API through call_notification.py and run seevents.py in loop using run.sh(see …

sklearn Pipeline: argument of type ColumnTransformer is not iterable

I am attempting to use a pipeline to feed an ensemble voting classifier as I want the ensemble learner to use models that train on different feature sets. For this purpose, I followed the tutorial avai…