Function Class API
4. API Reference: The `Function` Class
Initialization
A Function is initialized with its highest degree.
# Creates a placeholder for a cubic function (degree 3)my_func = polysolve.Function(3)
The function is not usable until its coefficients are set.
# f(x) = 4x³ - 2x² + 0x - 9# v0.7.0 Update: Coefficients can also be complex numbers!# f(x) = (1+2j)x³ - 5jmy_func.set_coeffs([1+2j, 0, 0, -5j])
Properties
You can access the degree of the function.
my_func.degree # Returns 3my_func.largest_exponent # Also returns 3
Evaluation
Evaluate the function at a specific x-value.
# Calculate f(2) for f(x) = 2x² - 3x - 5f1 = polysolve.Function(2)f1.set_coeffs([2, -3, -5])y = f1.solve_y(2)print(y) # Output: -3.0
Calculus
Calculate the first derivative or the nth-order derivative.
# f(x) = x³ + 2x² + 5f_cubic = polysolve.Function(3)f_cubic.set_coeffs([1, 2, 0, 5])# First derivative: f'(x) = 3x² + 4xdf_dx = f_cubic.derivative()print(df_dx) # Output: 3x^2 + 4x# Second derivative: f''(x) = 6x + 4d2f_dx2 = f_cubic.nth_derivative(2)print(d2f_dx2) # Output: 6x + 4
Solving and Root-Finding
PolySolve 0.7.0 introduces get_roots(), the primary entry point for finding **all** roots (real and complex).
# f(x) = x² + 1f = polysolve.Function(2)f.set_coeffs([1, 0, 1])# Calculate all roots (returns complex128 array)# roots = [0.+1.j, 0.-1.j]roots = f.get_roots(options={"find_complex": True})print(roots)# You can still use the helper methods for specific needs:real_roots_only = f.get_real_roots()target_roots = f.solve_x(y_val=50) # Find x where f(x) = 50
Arithmetic Operations
Function objects support addition, subtraction, and multiplication. These operations now support **complex scalars** and polynomials with complex coefficients.
f1 = polysolve.Function(2)f1.set_coeffs([1, 2, 1]) # x² + 2x + 1f2 = polysolve.Function(1)f2.set_coeffs([3, -4]) # 3x - 4# Addition: (x² + 2x + 1) + (3x - 4) = x² + 5x - 3f_add = f1 + f2print(f"Addition: {f_add}")# Subtraction: (x² + 2x + 1) - (3x - 4) = x² - x + 5f_sub = f1 - f2print(f"Subtraction: {f_sub}")# Multiplication: (x² + 2x + 1) * (3) = 3x² + 6x + 3f_mul_scalar = f1 * 3print(f"Scalar Multiplication: {f_mul_scalar}")# Function Multiplication: (x² + 2x + 1) * (3x - 4)f_mul_func = f1 * f2print(f"Function Multiplication: {f_mul_func}")
