I am new with python also new with this forum.
I have searched this topic but didn't give me better solutions (may be my search skill is poor)
Then I modified to
In my understanding, changing x in def locally will not change the x value outside the def.
Then I made changes like this.
But adds one xi variable, and manipulates zero with smallest float value.
I think this is not a good approach.
Please advise with better solution.
Thank you in advance.
I have searched this topic but didn't give me better solutions (may be my search skill is poor)
import numpy as np from scipy import special def somb(x): return 0.5 if x == 0.0 else special.j1(x) / x x = np.linspace(-1, 1, 3) print(x) y = somb(x) print(x) print(y)
Output:ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
If I change toimport numpy as np from scipy import special def somb(x): return 0.5 if (x == 0.0).all() else special.j1(x) / x x = np.linspace(-1, 1, 3) print(x) y = somb(x) print(x) print(y)
Output:[-1. 0. 1.]
[-1. 0. 1.]
[0.44005059 nan 0.44005059]
Warnings:
RuntimeWarning: invalid value encountered in true_divide
return 0.5 if (x == 0.0).all() else special.j1(x) / x
The return value still give a nan at x==0.Then I modified to
import numpy as np from scipy import special def somb(x): x[x==0] = np.finfo(float).smallest_normal return special.j1(x) / x x = np.linspace(-1, 1, 3) print(x) y = somb(x) print(x) print(y)
Output:[-1. 0. 1.]
[-1.00000000e+000 2.22507386e-308 1.00000000e+000]
[0.44005059 0.5 0.44005059]
No warnings/errors and the results are as expected, but changing the x values.In my understanding, changing x in def locally will not change the x value outside the def.
Then I made changes like this.
import numpy as np from scipy import special def somb(x): xi = x * 1.0 xi[x==0] = np.finfo(float).smallest_normal return special.j1(xi) / xi x = np.linspace(-1, 1, 3) print(x) y = somb(x) print(x) print(y)
Output:[-1. 0. 1.]
[-1. 0. 1.]
[0.44005059 0.5 0.44005059]
This was great.But adds one xi variable, and manipulates zero with smallest float value.
I think this is not a good approach.
Please advise with better solution.
Thank you in advance.