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
# Note: The list must contain degree + 1 elements.
my_func.set_coeffs([4, -2, 0, -9])

Properties

You can access the degree of the function.

my_func.degree  # Returns 3
my_func.largest_exponent # Also returns 3

Evaluation

Evaluate the function at a specific x-value.

# Calculate f(2) for f(x) = 2x² - 3x - 5
f1 = 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² + 5
f_cubic = polysolve.Function(3)
f_cubic.set_coeffs([1, 2, 0, 5])

# First derivative: f'(x) = 3x² + 4x
df_dx = f_cubic.derivative()
print(df_dx) # Output: 3x^2 + 4x

# Second derivative: f''(x) = 6x + 4
d2f_dx2 = f_cubic.nth_derivative(2)
print(d2f_dx2) # Output: 6x + 4

Solving and Root-Finding

This is the core feature of PolySolve. You can find the x-values for any given y-value using a powerful genetic algorithm.

# Find x where f(x) = 50, for f(x) = 3x² - 1
f = polysolve.Function(2)
f.set_coeffs([3, 0, -1])

# This finds x-values that result in y=50
x_solutions = f.solve_x(y_val=50)
print(x_solutions) # Will show values approximate to 4.12 and -4.12

# get_real_roots() is a convenient shortcut for solve_x(y_val=0)
roots = f.get_real_roots()
print(roots) # Will show values approximate to 0.577 and -0.577

Arithmetic Operations

Function objects support addition, subtraction, and multiplication.

f1 = polysolve.Function(2)
f1.set_coeffs([1, 2, 1]) # x² + 2x + 1

f2 = polysolve.Function(1)
f2.set_coeffs([3, -4])   # 3x - 4

# Addition: (x² + 2x + 1) + (3x - 4) = x² + 5x - 3
f_add = f1 + f2
print(f"Addition: {f_add}")

# Subtraction: (x² + 2x + 1) - (3x - 4) = x² - x + 5
f_sub = f1 - f2
print(f"Subtraction: {f_sub}")

# Multiplication: (x² + 2x + 1) * (3) = 3x² + 6x + 3
f_mul_scalar = f1 * 3
print(f"Scalar Multiplication: {f_mul_scalar}")

# Function Multiplication: (x² + 2x + 1) * (3x - 4)
f_mul_func = f1 * f2
print(f"Function Multiplication: {f_mul_func}")