1

I have a for loop which calculates a square root but for some iterations (i.e. for some values of Pos1) the expression under the square root is negative and hence the square root is impossible to calculate in the real domain and Python returns the "ValueError: math domain error" for the whole loop. Instead, I would like it to make the calculation whenever it is possible (when the expression under the square root is positive) and otherwise, print some message for example "unable to calculate sqrt" for those iterations when the value is negative.

for i in range(len(Pos1)):
    theta3_1=math.sqrt(1-math.pow(((math.pow((x3-2*Pos1[0][i]),2)+math.pow((y3-2*Pos1[1][i]),2)-math.pow(L[1],2)-math.pow(L[2],2))/(2*L[1]*L[2])),2))
Blazej Kowalski
  • 367
  • 1
  • 6
  • 16
  • 2
    In the [Pyton tutorial](https://docs.python.org/3/tutorial/index.html), search for `try` ,,, `except` – gboffi Jul 13 '17 at 10:21
  • 1
    Otherwise use a temporary variable `theta_sqd = ...` followed by `if theta_sqd>0: theta=sqrt(theta_sqd) ; ...` – gboffi Jul 13 '17 at 10:31
  • 1
    My last comment. I swear: the try/except stuff in the tutorial is [here](https://docs.python.org/3/tutorial/errors.html) – gboffi Jul 13 '17 at 10:35

0 Answers0