Код на Python работает только с небольшими значениямиPython

Программы на Python
Ответить
Anonymous
 Код на Python работает только с небольшими значениями

Сообщение Anonymous »

У меня есть код Python, который хорошо работает с небольшими целочисленными значениями для моей основной переменной (обозначенной как m), но работает очень медленно с более высокими значениями.
Предназначенными выходными данными являются коэффициенты A (m,i) в степенном ряду, определяемом производящей функцией (см. ссылку: https://sites.math.rutgers.edu/~zeilber ... coupon.pdf)
Изображение

Для справки код дает следующий ответ для m =6:
For a collection with 6 categories and number of copies (i) from = 1 to 10:
Expected number of essays: 14.700000
Expected number of elements with 1 copies: 2.45000
Expected number of elements with 2 copies: 1.29694
Expected number of elements with 3 copies: 0.927792
Expected number of elements with 4 copies: 0.584912
Expected number of elements with 5 copies: 0.341049
Expected number of elements with 6 copies: 0
Expected number of elements with 7 copies: 0
Expected number of elements with 8 copies: 0
Expected number of elements with 9 copies: 0
Expected number of elements with 10 copies: 0

Однако выполнение кода занимает много времени по мере увеличения m и зависает при значениях больше 6.
Мой код приведен ниже. Я хотел бы понять, почему более высокие значения m приводят к увеличению времени выполнения.
Есть предложения по отладке?
import sympy as sp

# Specify number of categories using m
m = 7

# Specify interval of expected number of copies o) using i variable for minimum and maximum values
i_min = 1
i_max = 10

# Calculate expected number of essays to get at least one copy of each category.
E_m = m * sum(1 / i for i in range(1, m + 1))

# Define auxiliary variable t for Taylor Expansion
t = sp.symbols('t')

# Definition of generative formula
def calculate_probability(m, i_min, i_max):
# Generative formula components
numerator = sp.factorial(m)
denominator = 1
# Denominator as product of (j - t) for j=2 to m
for j in range(2, m + 1):
denominator *= (j - t)

# Ratio of generative formula
generative = t - 1 + numerator / denominator

# Taylor expansion for generative formula as power series
expansion = sp.series(generative, t, 0, m) # using t=0, expansion to t^m

# Shown values for m and interval using i_min to i_max
print(f"For a collection with {m} categories and number of copies (i) from = {i_min} to {i_max}:")

# Show expansion
#print(f"Taylor expansion for generative series:")
#print(expansion)

# Show result
print(f"Expected number of essays: {E_m:.6f}")

# Iterate over interval of i (from i_min to i_max)
for i in range(i_min, i_max + 1):
# Get coefficient of t^i
coef_ti = expansion.coeff(t, i)

# Show expected number rounded to 6 decimals
probability_num = coef_ti.evalf(6)

# Expected number of elements with exactly i copies.
print(f"Expected number of elements with {i} copies: {probability_num}")

# Call function to calculate probability for referred interval
calculate_probability(m, i_min, i_max)


Подробнее здесь: https://stackoverflow.com/questions/792 ... all-values
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»