Solving Equations using Numpy

Solving Equations Using NumPy

Solving Simultaneous and Higher-Order Equations Using NumPy

Like My Content?
Hey friend 😊 If you enjoy my posts and feel like buying me a cup of chai ☕, just scan the QR and send whatever you like. It’s totally optional, but it really keeps me motivated to share more. Thank you so much!
Open QR — Scan or save

Solving simultaneous equations is a common problem in many fields, such as engineering, physics, economics, and mathematics. NumPy, a powerful Python library, provides an efficient and straightforward way to solve these equations.

Introduction to Simultaneous Equations

Simultaneous equations are a set of equations with multiple variables solved together because they share variables. Example:

2x + 3y = 8
3x + 4y = 11

Using NumPy to Solve Simultaneous Equations

NumPy's numpy.linalg.solve function solves systems of linear equations of the form A x = b:

import numpy as np

# Coefficient matrix
A = np.array([[2, 3], [3, 4]])

# Constant matrix
b = np.array([8, 11])

# Solve the system
solution = np.linalg.solve(A, b)
print("Solution:", solution)
Solution: [1. 2.]

Example with a Larger System

A = np.array([[1, 1, 1],
                  [0, 2, 5],
                  [2, 5, -1]])
b = np.array([6, -4, 27])

solution = np.linalg.solve(A, b)
print("Solution:", solution)
Solution: [10. -1. -3.]

Solving Higher-Order Polynomial Equations Using NumPy

Higher-order polynomial equations involve powers of x greater than two. NumPy's numpy.roots function helps find the roots efficiently.

Example: Cubic Polynomial

coefficients = [2, -6, 2, -1]
roots = np.roots(coefficients)
print("Roots:", roots)
Roots: [ 2.07313218+0.j -0.28072789+0.76953195j -0.28072789-0.76953195j]

Example: Quartic Polynomial

coefficients = [1, -3, 2, -1, 1]
roots = np.roots(coefficients)
print("Roots:", roots)
Roots: [ 1.94385634+0.j -0.42018079+0.60629073j -0.42018079-0.60629073j 0.89650524+0.j ]

Example: Quintic Polynomial

coefficients = [1, -4, 3, -2, 1, -1]
roots = np.roots(coefficients)
print("Roots:", roots)
Roots: [ 2.34191609+0.j 0.93725817+0.50771233j 0.93725817-0.50771233j -0.10821622+0.4734558j -0.10821622-0.4734558j ]
Contact Varanasi Software Junction
Contact us for software training, education or development

Post a Comment

0 Comments

Me