'How to change function values inside an if loop [closed]
import numpy as np
from ufl import cofac, sqrt
def f(X):
fx = sqrt(X[0]**2+X[1]**2)
return fx
X = np.array([1.0, 2.0])
Y = f(X)
print(Y)
if f(X)<=3:
f(X)=0.0
print(f(X))
exit()
The above function calculates the distance of a point from the origin. If the distance is less than 3 units, I need to assign the value 0.0 to the function.
But the above code gives me no difference in results before and after the "if" loop. How to assign values to functions inside an if loop?
Solution 1:[1]
Sounds like you want the f()
function to return different results depending on the values in X.
def f(X):
fx = sqrt(X[0]**2+X[1]**2)
if fx > 3:
return fx
else:
return 0.0
Solution 2:[2]
As @mkrieger1 said; if you are trying to assign the value to f(X) you have to use =
operator.
Moreover, you cannot assign the value to function, instead you can assign value to Y
and print.
import numpy as np
from ufl import cofac, sqrt
def f(X):
fx = sqrt(X[0]**2+X[1]**2)
return fx
X = np.array([1.0, 2.0])
Y = f(X)
print(f(X))
if f(X)<=3:
Y=0.0
print(Y)
Here, is the link:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | John Gordon |
Solution 2 |