Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ecosdelfuturo/4d412b05ca8c95a7628b275da622abfa to your computer and use it in GitHub Desktop.
Save ecosdelfuturo/4d412b05ca8c95a7628b275da622abfa to your computer and use it in GitHub Desktop.
A simple way to estimate the max/min of a function

I've struggled to figure out a simple way to estimate the maximum or minimum of a non-trivial function in #Python but, finally, the most convenient way seems to be

optimize.minimize_scalar(f, bounds=(x1,x2), method='bounded')

My particular problem was to find the maximum of the spectral irradiance of a #blackbody

The code used

from scipy import optimize
from scipy import constants
import numpy as np

h = constants.h
c = constants.c
k = constants.k
pi = constants.pi
T = 5800

def f(x):
    #return -1e-9*2*pi*h*c**2*(x*1e-9)**(-5)/(np.exp(h*c*1e9/(x*k*T))-1)
    return -2*pi*h*c**(-2)*(1e9*c/x)**3/(np.exp(h*(1e9*c/x)/(k*T))-1)

result = optimize.minimize_scalar(f, bounds=(500, 1500), method='bounded')

print(result.x)

In this particular case, the solution can be checked by equalling the derivative to zero. It works with this particular function but one has to be very careful with the definitions.

In the code below the way I have made it work.

from sympy import Symbol, lambdify
from math import e
from scipy.optimize import root_scalar

f = Symbol('f')
Bnu = 2*h*c**(-2)*(f)**3/(e**(h*(f)/(k*T))-1)
DBnu = Bnu.diff(f)
lam_DBnu = lambdify(f, DBnu)
sol = root_scalar(lam_DBnu, bracket=[c/1000e-9, c/100e-9])
1e9*c/sol.root

Original post: https://mstdn.social/@ecosdelfuturo/112852523104349091

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment