SciPy Exercises
Problem 1: In machine learning and physics, you often need to find the lowest possible point of a mathematical function. Let’s say you have the equation $f(x) = x^2 + x + 2$. Use SciPy to find the exact value of $x$ that results in the minimum value for this function.
from scipy.optimize import minimize
# 1. Define the mathematical function
def my_function(x):
return x**2 + x + 2
# 2. Provide an initial guess for x (the algorithm needs a starting point)
initial_guess = 0.0
# 3. Ask SciPy to find the minimum
result = minimize(my_function, initial_guess)
print("Optimization Result:
", result.message)
print(f"The minimum occurs at x = {result.x[0]:.4f}")
Problem 2: You are analyzing a test where the scores follow a perfectly normal distribution (a bell curve). The average (mean) score is 50, and the standard deviation is 10. What is the exact probability of a student scoring exactly 60 or lower?
from scipy.stats import norm
# 1. Define the distribution parameters
mean = 50
std_dev = 10
# 2. Use the Cumulative Distribution Function (CDF)
# The CDF calculates the area under the curve up to a specific point
score_to_check = 60
probability = norm.cdf(score_to_check, loc=mean, scale=std_dev)
print(f"The probability of scoring {score_to_check} or less is: {probability * 100:.2f}%")
Problem 3: Calculate the definite integral of the function $f(x) = 3x^2$ from $x = 0$ to $x = 2$. In visual terms, you are finding the exact area under this curve between those two boundaries.(Note: If you do the calculus by hand, the exact answer is 8).
from scipy.integrate import quad
# 1. Define the function to integrate
def curve(x):
return 3 * x**2
# 2. Perform the integration (quadrature) from 0 to 2
# 'quad' returns two values: the estimated answer, and the estimated error margin
area, error = quad(curve, 0, 2)
print(f"Calculated Area: {area}")
print(f"Margin of Error: {error}")