英文:
Generate a random polynomial using Sympy
问题
I'd like to generate a polynomial of a random degree with random coefficients using sympy
.
If possible, I'd also like to control the percentage of coefficients that are zero. I know that something similar is possible for Matrices using randMatrix
.
英文:
I'd like to generate a polynomial of a random degree with random coefficients using sympy
.
If possible, I'd also like to control the percentage of coefficients that are zero. I know that something similar is possible for Matrices using randMatrix
.
答案1
得分: 1
我找到了以下内置方法。
https://docs.sympy.org/latest/modules/polys/reference.html#sympy.polys.specialpolys.random_poly
一个随机多项式,其次数最多为5,整数系数在-10和10之间。
from sympy.polys.specialpolys import random_poly
from sympy abc import x
from random import randint
n = randint(0, 5)
p = random_poly(x, n, -10, 10)
但最终,我最终编写了自己的方法以控制百分比。
英文:
I found the following in-built method.
https://docs.sympy.org/latest/modules/polys/reference.html#sympy.polys.specialpolys.random_poly
A random polynomial of degree at most 5 with integer coefficient between -10 and 10.
from sympy.polys.specialpolys import random_poly
from sympy abc import x
from random import randint
n = randint(0,5)
p = random_poly(x,n,-10,10)
But ultimately, I ended up writing my own to control the percentage.
答案2
得分: 1
你已经发布了如何生成随机多项式的方法。不幸的是,没有内置选项来控制零系数的百分比。但你可以像这样控制它们:
from sympy.polys.specialpolys import random_poly
from sympy.abc import x
import random
from random import randint
degree = randint(0,5)
zero_percentage = 0.3
poly = random_poly(x, degree, -10, 10, polys=True)
coefficients = poly.all_coeffs() # 获取多项式的所有系数
zero_count = int(len(coefficients) * zero_percentage)
zero_indices = random.sample(range(len(coefficients)), zero_count)
for i in zero_indices:
coefficients[i] = 0
modified_poly = sum(coefficients[i] * x**i for i in range(len(coefficients))) # 构造修改后的多项式
print(modified_poly)
英文:
You have already posted how to generate a random polynomial. Sadly there's no built-in option to control the percentage of zero coefficients. But you can control them like this:
from sympy.polys.specialpolys import random_poly
from sympy.abc import x
import random
from random import randint
degree = randint(0,5)
zero_percentage = 0.3
poly = random_poly(x, degree, -10, 10, polys=True)
coefficients = poly.all_coeffs() # get all the coefficients of the polynomial
zero_count = int(len(coefficients) * zero_percentage)
zero_indices = random.sample(range(len(coefficients)), zero_count)
for i in zero_indices:
coefficients[i] = 0
modified_poly = sum(coefficients[i] * x**i for i in range(len(coefficients))) # construct the modified polynomial
print(modified_poly)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论