Python,how to solve ValueError: math domain error

Python,how to solve ValueError: math domain error

我正在尝试获取此代码的结果:

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()

我看了这个post: ValueError: math domain error

我的想法可能是使用 abs() 和 round()。

没解决

出现这种情况是因为cos(angle)等于-0.9680080671170238,所以2 * cos(angle)-1.9360161342340476,也就是说sqrt(2 * cos(angle))是虚数。

内置函数 math.sqrt 无法处理负参数,因此会抛出 ValueError。

如果你真的想求一个负数的平方根,你可以使用cmath库中的sqrt方法:

from cmath import sqrt

在这个例子中会给出:

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