Python,如何解决ValueError:数学域错误

2024-04-25 13:12:00 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我看了这篇文章: ValueError: math domain error

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

这并没有解决问题


Tags: infromforabmathsqrtfindpoint
1条回答
网友
1楼 · 发布于 2024-04-25 13:12:00

这是因为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))

相关问题 更多 >