0
0
NumPydata~5 mins

NumPy with SciPy

Choose your learning style9 modes available
Introduction

NumPy helps us work with numbers and arrays easily. SciPy builds on NumPy to give us more tools for math and science tasks.

When you want to do fast math on lists of numbers.
When you need to solve math problems like integration or optimization.
When you want to work with scientific data like signals or images.
When you want to use ready-made math functions without writing them yourself.
Syntax
NumPy
import numpy as np
from scipy import integrate, optimize

# Use NumPy to create arrays
arr = np.array([1, 2, 3])

# Use SciPy to do math tasks
result = integrate.quad(lambda x: x**2, 0, 1)

# Use SciPy to find minimum of a function
min_result = optimize.minimize(lambda x: (x-3)**2, [0])

NumPy is mainly for arrays and basic math.

SciPy adds special math tools like integration and optimization.

Examples
This example uses SciPy's integrate.quad to find the area under the curve y = x² between 0 and 1.
NumPy
import numpy as np
from scipy import integrate

# Calculate area under curve y = x^2 from 0 to 1
area, error = integrate.quad(lambda x: x**2, 0, 1)
print(area)
This example uses SciPy's optimize.minimize to find the value of x that minimizes the function (x-5)².
NumPy
import numpy as np
from scipy import optimize

# Find x that makes (x-5)^2 smallest
result = optimize.minimize(lambda x: (x-5)**2, [0])
print(result.x)
This example shows how to create a NumPy array and square each element easily.
NumPy
import numpy as np

# Create a NumPy array and do math
arr = np.array([1, 2, 3, 4])
squared = arr ** 2
print(squared)
Sample Program

This program shows how to create a NumPy array and use SciPy to calculate an integral and find a minimum value of a function.

NumPy
import numpy as np
from scipy import integrate, optimize

# Create a NumPy array
numbers = np.array([0, 1, 2, 3, 4])

# Use SciPy to integrate x^3 from 0 to 2
area, error = integrate.quad(lambda x: x**3, 0, 2)

# Use SciPy to find minimum of (x-1)^2 + 2
min_result = optimize.minimize(lambda x: (x-1)**2 + 2, [0])

print(f"Array: {numbers}")
print(f"Integral of x^3 from 0 to 2: {area}")
print(f"Minimum of function: {min_result.x[0]}")
OutputSuccess
Important Notes

NumPy arrays are faster and easier to use than regular Python lists for math.

SciPy functions often return extra info like error estimates.

Always import SciPy modules you need separately (like integrate or optimize).

Summary

NumPy helps with fast and easy number arrays.

SciPy adds many useful math tools on top of NumPy.

Use them together for scientific and math problems.