user12177026
user12177026

Reputation:

Python,how to solve ValueError: math domain error

I'm trying to get the result of this code:

from math import cos, sin, atan2, sqrt
from numpy import rad2deg


dis_ab= 531466.5079260713
mid=(531353.2565883757, 10971.133034496568)
mid_angle_from_x_in_rad=1.5501517288292364
mid_angle_from_x_in_deg=88.8171516668233
gdt1_x=761708.6575534055
gdt1_y=3679240.5391967976
uav_x= 230355.40096502978
uav_y=3668269.406162301
angle=178.8171516668233




def find_point_for_second_gdt():
    dist_ab = sqrt(((gdt1_x - uav_x) ** 2) + ((gdt1_y - uav_y) ** 2))

    mid = (gdt1_x - uav_x), (gdt1_y - uav_y)
    mid_angle_from_x_in_rad = atan2(mid[0], mid[1])
    mid_angle_from_x_in_deg = (rad2deg(mid_angle_from_x_in_rad))

    angle = 90 + mid_angle_from_x_in_deg


    x = gdt1_x + (dis_ab * sqrt(2 * cos(angle)))
    y = gdt1_y + (dis_ab * sqrt(2 * sin(angle)))

    end_xy = (x, y)

    point_in_lat_lon = convert_to_lat_lon(end_xy)

    print(point_in_lat_lon)

output:
      Traceback (most recent call last):
  File "/home/yovel/PycharmProjects/TriangulationCalc/find_2nd_position.py", line 36, in <module>
    find_point_for_second_gdt()
    File "/home/yovel/PycharmProjects/TriangulationCalc/find_2nd_position.py", line 26, in find_point_for_second_gdt
    x = gdt1_x + (dis_ab * sqrt(2 * cos(angle)))
    ValueError: math domain erro

find_point_for_second_gdt()

I looked at this post: ValueError: math domain error

my thought by this was maybe to use abs() and round().

It didn't solve it.

Upvotes: 1

Views: 1147

Answers (1)

CDJB
CDJB

Reputation: 14516

This occurs because cos(angle) equals -0.9680080671170238, so 2 * cos(angle) is -1.9360161342340476, which means that sqrt(2 * cos(angle)) is imaginary.

The builtin math.sqrt can't handle negative arguments, so it throws a ValueError.

If you really want to find the square root of a negative number, you can use the sqrt method from the cmath library:

from cmath import sqrt

which in this example would give:

>>> end_xy
((761708.6575534055+739486.7340101058j), (4055734.2602401497+0j))

Upvotes: 2

Related Questions