Skip to content

Instantly share code, notes, and snippets.

@ThreePointSquare
Created December 5, 2023 17:18
Show Gist options
  • Save ThreePointSquare/ed7517ddab2d615754634b58927573b7 to your computer and use it in GitHub Desktop.
Save ThreePointSquare/ed7517ddab2d615754634b58927573b7 to your computer and use it in GitHub Desktop.
Taylor Polynomial Using Numpy and Rhino Python
#! python3
# r: numpy
import numpy as np
import rhinoscriptsyntax as rs
def get_cosine_points(x):
return x, np.cos(x)
def get_taylor_polynomial_points(x, degree):
coefficients = [1 / np.math.factorial(i) if i % 2 == 0 else 0 for i in range(degree + 1)]
y = np.polyval(coefficients, x)
return x, y
x_values = np.linspace(-6, 6, 50)
# Get points for y = cos(x)
cosine_points = get_cosine_points(x_values)
# Print the points for reference
print("Cosine Points:")
for x, y in zip(cosine_points[0], cosine_points[1]):
print(f"({x}, {y})")
# Get points for degree 2 Taylor polynomial
taylor_2_points = get_taylor_polynomial_points(x_values, 2)
# Print the points for reference
print("\nTaylor Degree 2 Points:")
for x, y in zip(taylor_2_points[0], taylor_2_points[1]):
print(f"({x}, {y})")
# Get points for degree 4 Taylor polynomial
taylor_4_points = get_taylor_polynomial_points(x_values, 4)
# Print the points for reference
print("\nTaylor Degree 4 Points:")
for x, y in zip(taylor_4_points[0], taylor_4_points[1]):
print(f"({x}, {y})")
# Convert points to Rhino points and create curves
cosine_points_rhino = [rs.CreatePoint(x, y, 0) for x, y in zip(cosine_points[0], cosine_points[1])]
taylor_2_points_rhino = [rs.CreatePoint(x, y, 0) for x, y in zip(taylor_2_points[0], taylor_2_points[1])]
taylor_4_points_rhino = [rs.CreatePoint(x, y, 0) for x, y in zip(taylor_4_points[0], taylor_4_points[1])]
# Build curves from Rhino points
cosine_curve = rs.AddInterpCurve(cosine_points_rhino)
rs.ObjectColor(cosine_curve, rs.CreateColor(255,0,0))
taylor_2_curve = rs.AddInterpCurve(taylor_2_points_rhino)
rs.ObjectColor(taylor_2_curve, rs.CreateColor(0,255,0))
taylor_4_curve = rs.AddInterpCurve(taylor_4_points_rhino)
rs.ObjectColor(taylor_4_curve, rs.CreateColor(0,0,255))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment