你的问题是你的代码格式太差了,你看不到你的括号错误。在
错误1
例如,这一行:sideA = math.sqrt((x - mousex)**2)+((y - mousey)**2)
如果格式正确,如下所示:
^{pr2}$
当你去掉多余的括号,你可以更清楚地看到发生了什么:sideA = math.sqrt((x - mousex) ** 2) + (y - mousey) ** 2
你只需要把你两边的平方数传给math.sqrt(),然后再加上第二边的平方。它应该是:sideA = math.sqrt((x - mousex) ** 2 + (y - mousey) ** 2)
甚至更好:sideA = math.hypot(x - mousex, y - mousey)
错误2
然后这一行:cos = float(sideA**2)-(sideB**2)-(sideC**2)/(-2*(sideB*sideC))
有一个类似的问题-你在前三个项的周围缺少圆括号,而你只把C边的平方除以2bc。它应该是:cos = (sideA ** 2 - sideB ** 2 - sideC ** 2) / ( -2 * sideB * sideC)
解决方案
由于上述原因,您没有正确计算余弦,所以您传递给math.acos()的内容超出了余弦的允许范围(余弦始终在-1 <= cos A <= 1范围内),所以它给了您域错误。把你的值打印出来会让你看到你得到的东西真的很奇怪。在
这是您的程序的一个固定的工作版本,修改后只直接为mousex和mousey设置值:#!/usr/bin/env python
import math
x, y = 100, 100
centerX, centerY = x + 50, y + 50
mousex, mousey = 100,150
sideA = math.hypot(x - mousex, y - mousey);
sideB = math.hypot(centerX - mousex, centerY - mousey)
sideC = math.hypot(centerX - x, centerY - y)
cosA = (sideB ** 2 + sideC ** 2 - sideA ** 2) / (2 * sideB * sideC)
angle = math.acos(cosA)
print "sideA: %.2f, sideB: %.2f, sideC: %.2f" % (sideA, sideB, sideC)
print "cosA: %.6f" % (cosA)
print "angle: %.2f radians, %.2f degrees" % (angle, math.degrees(angle))
哪些输出:paul@horus:~/src/sandbox$ ./angle.py
sideA: 50.00, sideB: 50.00, sideC: 70.71
cosA: 0.707107
angle: 0.79 radians, 45.00 degrees
paul@horus:~/src/sandbox$
我已经自由地重新安排了你的余弦规则计算,以消除需要否定分母。在