2

I have the following negative quadratic equation

-0.03402645959398278x^{2}+156.003469x-178794.025

I want to know if there is a straight way (using numpy/scipy libraries or any other) to get the value of x when the slope of the derivative is zero (the maxima). I'm aware I could:

  • change the sign of the equation and apply the scipy.optimize.minima method or
  • using the derivative of the equation so I can get the value when the slope is zero

For instance:

from scipy.optimize import minimize


quad_eq = np.poly1d([-0.03402645959398278, 156.003469, -178794.025])

############SCIPY####################
neg_quad_eq = np.poly1d(np.negative(quad_eq))
fit = minimize(neg_quad_eq, x0=15)
slope_zero_neg = fit.x[0]
maxima = np.polyval(quad_eq, slope_zero_neg)
print(maxima)

##################numpy######################
import numpy as np

first_dev = np.polyder(quad_eq)
slope_zero = first_dev.r
maxima = np.polyval(quad_eq, slope_zero)
print(maxima)

Is there any straight way to get the same result? print(maxima)

AGH
  • 300
  • 3
  • 12

1 Answers1

0

You don't need all that code... The first derivative of a x^2 + b x + c is 2a x + b, so solving 2a x + b = 0 for x yields x = -b / (2a) that is actually the maximum you are searching for

import numpy as np
import matplotlib.pyplot as plt

def func(x, a=-0.03402645959398278, b=156.003469, c=-178794.025):
    result = a * x**2 + b * x + c
    return result

def func_max(a=-0.03402645959398278, b=156.003469, c=-178794.025):
    maximum_x = -b / (2 * a)
    maximum_y = a * maximum_x**2 + b * maximum_x + c
    return maximum_x, maximum_y

x = np.linspace(-50000, 50000, 100)

y = func(x)
mx, my = func_max()

print('maximum:', mx, my)

maximum: 2292.384674478263 15.955750522436574

and verify

plt.plot(x, y)
plt.axvline(mx, color='r')
plt.axhline(my, color='r')

enter image description here

Max Pierini
  • 2,027
  • 11
  • 17