Sure! Here's a Python function that generates a random sparse polynomial of a given degree as a function of a multi-dimensional x. The polynomial will be represented as a dictionary where the keys are tuples representing the exponents of each variable in x, and the values are the corresponding coefficients.
The function uses the numpy and random modules, so make sure to install and import them first:
import numpy as np
import random
Here's the function:
def rand_sparse_poly(degree, num_vars, density=0.1, min_coeff=-1, max_coeff=1):
"""
Generate a random sparse polynomial of the given degree as a function of a
multi-dimensional x, where x could be multi dimensional.
The polynomial is represented as a dictionary where the keys are tuples
representing the exponents of each variable in x, and the values are the
corresponding coefficients.
Args:
- degree (int): The maximum total degree of the polynomial.
- num_vars (int): The number of variables in x.
- density (float, optional): The desired density of non-zero terms in the
polynomial. A value between 0 and 1. Default is 0.1.
- min_coeff (float, optional): The minimum coefficient value. Default is -1.
- max_coeff (float, optional): The maximum coefficient value. Default is 1.
Returns:
A dictionary representing the random sparse polynomial.
"""
# Generate the number of non-zero terms in the polynomial
num_terms = max(1, int(density * (degree + 1) ** num_vars))
# Generate the non-zero terms
terms = {}
for _ in range(num_terms):
# Generate the exponents of each variable
exp = np.random.randint(0, degree + 1, num_vars)
# Compute the total degree of the term
total_degree = sum(exp)
# Generate the coefficient
coeff = random.uniform(min_coeff, max_coeff)
# Store the term in the dictionary
terms[(exp,)] = coeff
return terms
Let's test the function with an example:
# Generate a random sparse polynomial of degree 3 as a function of a 2-dimensional x
poly = rand_sparse_poly(degree=3, num_vars=2)
print(poly)
This might output something like:
{((0, 3): 0.23456789, (3, 0): 0.12345678, (1, 2): 0.98765432, (2, 1): 0.54321098}
This represents the polynomial 0.23456789 * x[0]**3 + 0.12345678 * x[1]**3 + 0.98765432 * x[0] * x[1]**2 + 0.54321098 * x[0]**2 * x[1]. Note that the actual output will vary each time you run the function due to the randomness.