Click here to Skip to main content
15,902,198 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In my code I am required to use a piecewise function within another defined function. But I am having some trouble attempting this. The code I have supplied obviously does not work but I structured it this way so you can see what I am going for.

def f(λ,a,u,o1,o2):
    if (λ < u): return o = o1
    else: return o = o2
    return a*math.exp((λ-u)^2/(-2*o^2))


My main function is of λ, and the piecewise function is the o values. Where I want them to take different values when λ is greater and less than u.

I thought there would be something online for this but I can't seem to find anything that fits this specific example.

What I have tried:

An idea was to define the two functions (one for λ and the piecewise function) seperately. However, both of which rely on eachother so I figure they must be defined as one.

Another attempt I was convinced would work is;
def f(λ,a,u,o1,o2):
    return a*math.exp((λ-u)^2/(-2*(if λ<μ then σ1 else σ2)^2))


This is where I am now ^
Posted
Updated 6-Sep-21 1:58am

1 solution

Sounds like you're looking for a "conditional expression":
6. Expressions — Python 3.9.7 documentation[^]
Python
def f(λ,a,u,o1,o2):
    o = o1 if λ < u else o2
    return a*math.exp((λ-u)^2/(-2*o^2))
 
Share this answer
 
Comments
Ryan Peen 6-Sep-21 8:07am    
Ugh! I was so close. Thankyou :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900