Maximum of Equation -

Engineering Numerical Methods


We will find the maximum for f(x) = 2*sin(x) + 1

Since scipy.optimize is designed for minimization, we can find a maximum by minimizing the negative of the function. We will find the maximum for f(x) = 2*sin(x) + 1 . This approach works for any smooth function you want to maximize with SciPy. Please note that many equations have more than one maximum. Suggested reading is Numerical Methods for Engineers, Fifth Edition by Chapra and Canale.



How it works:
Function definition: f(x) is your target function.
Negation trick: We pass -f(x) to minimize_scalar to turn the maximum problem into a minimum problem.
Bounds: (0, 2π) ensures we search one full sine wave period.
Method: "bounded" is efficient for bounded scalar optimization.
Result: result.x is the x where the maximum occurs, and result.fun is the minimized value of -f(x).

  
# For  f(x) = 2*sin(x) + 1 

import numpy as np
from scipy.optimize import minimize_scalar
import matplotlib.pyplot as plt

# Define the function to maximize
def f(x):
    return 2 * np.sin(x) + 1  

#Since minimize_scalar finds a minimum, 
# we minimize -f(x) for maximum.

result = minimize_scalar(lambda x: -f(x), bounds=(0, 2*np.pi), method='bounded')

if result.success:
    x_max = result.x
    f_max = f(x_max)
    print(f"Max value: {f_max:.6f} at x = {x_max:.6f} radians")
else:
    print("Optimization failed:", result.message)
    
# For  f(x) = 2*sin(x) + 1 

import numpy as np
from scipy.optimize import minimize_scalar
import matplotlib.pyplot as plt

# Define the function to maximize
def f(x):
    return 2 * np.sin(x) + 1  

#Since minimize_scalar finds a minimum, 
# we minimize -f(x) for maximum.

result = minimize_scalar(lambda x: -f(x), bounds=(0, 2*np.pi), method='bounded')

if result.success:
    x_max = result.x
    f_max = f(x_max)
    print(f"Max value: {f_max:.6f} at x = {x_max:.6f} radians")
else:
    print("Optimization failed:", result.message)
    
#Output: Max value: 3.000000 at x = 1.570798 radians

#Plot
x=np.arange(-5,5,.01)
funcx=2*np.sin(x)+1
plt.plot(x,funcx)
plt.show()
 
    



Plot f(x) = 2*sin(x) + 1












Introduction to Engineering Python: For First Year Engineering Students