How to find the root of a function within a range in python

116 Views Asked by At

I need to find the alpha value in [0,1] of a linear combination alpha*Id+(1-alpha)*M, where Id is the identity matrix, M is a given matrix, such that this linear combination has given mean.

At the moment I am using scipyt.optimize.fsolve but it does not admit the range [0,1] as an input. Any suggestion ?

1

There are 1 best solutions below

6
C-3PO On

You can define alpha using a sigmoid function:

alpha = 1/(1+exp(-x))

https://en.wikipedia.org/wiki/Sigmoid_function

Based on this definition, alpha will always be in the range [0, 1]. Then, you can change the target of the optimization in scipy.optimize.fsolve to calibrate the value of x instead of alpha directly.

The variable x is free of constraints, so any optimization method works.


PS. This technique is very common in machine learning.


PS2. Adding constraints to an optimizer is only important when they are not being fulfilled. So for example, if your alpha solution is already in the range [0,1], then you can keep the optimizer as it is.