Home > Net >  How can I solve a non continuous equation in python?
How can I solve a non continuous equation in python?

Time:12-01

I have a function:

p = np.arange(0,1,0.01)
EU = (((-(1.3 1-0.5)**(1.2-1.5)/(1-1.5)))**-1)*p   (((-(0.1 1-0.5)**(1.2-1.5)/(1-1.5)))**-1)*(1-p)

And I would like to solve this to get a value of p where EU == 0.5. My issue is that I checked manually and the p value is 0.4244, but in the function p jumps with steps of 0.01.

Now I'm fine with getting the closest p value where EU is closest to 0.5, but I'm worried the code will not find an answer, since none of the values from the p array will return exactly 0.5 for EU. How could I solve this?

CodePudding user response:

your function is a simple linear function, so it could be simply found by just a simple binary search, however if the funciton was more complex and you needed to really calculate the gradient and runt he optimization you could use torch or jax or any other autograd tools to do that

import torch
def func(p):
    return (((-(1.3 1-0.5)**(1.2-1.5)/(1-1.5)))**-1)*p   (((-(0.1 1-0.5)**(1.2-1.5)/(1-1.5)))**-1)*(1-p)


x = torch.tensor([0.1], requires_grad=True)
loss = 1
# 1e-7 example threshold for answer to stop
while loss > 1e-7:
    x.retain_grad()
    y = func(x)
    loss = (y - torch.tensor([0.5], requires_grad=True)) ** 2 
    # or use MSELoss from nn  
    loss.backward()
    x = x - 0.1 * x.grad # naive gradient decent with lr = 0.1

print(x.item())

0.42235034704208374
  • Related