Home > Back-end >  Exponential list of numbers with the total sum egal 100
Exponential list of numbers with the total sum egal 100

Time:12-16

I would like to generate an exponential (or linear) list of number (float or int) where the total sum = 100

More or less Like this one:

[2, 10, 18, 30, 40] total sum = 100

For now, i use this code to generate exponential (or linear) list of numbers, but i dont know the formula to get numbers with a total sum = 100

import numpy as np
l = np.logspace(0.1, 2, 10, endpoint=True)
#OR
l = np.linspace(1, 100, 10, endpoint=True)

Thanks for you help!

CodePudding user response:

import numpy as np
target_norm = 100
l = np.linspace(0, 10, 21, endpoint=True)
le = np.exp(l)
le_normed = target_norm*(le/np.sum(le))
print(f'{np.sum(le_normed)}') # 100 (=target_norm)

By making the sampling interval of l larger, you can scale the exponential.

We already saw that np.sum(le_normed) == target_norm but let's check if the results look plausible:

import matplotlib.pyplot as plt
plt.close('all')
fig = plt.Figure(figsize=(12, 3))
ax = fig.add_subplot(1,3,1)
ax.set_title("l")
ax.plot(l)
ax = fig.add_subplot(1,3,2)
ax.set_title('le')
ax.plot(le)
ax = fig.add_subplot(1,3,3)
ax.set_title('le_normed')
ax.plot(le_normed)
fig

Visualization of the transformation

  • Related