[英]Why does my code doesn't treat parallel vectors as such?
我编写了以下代码,旨在通知其用户两个给定向量是否平行/正交以及两个向量之间的角度是多少:
import math
from numpy import arccos, array, dot
def oracle(a, b):
n= 0
scalar = a[n]/b[n]
while n < len(a):
s = a[n]/b[n]
if s != scalar or (not s < (scalar + 0.001) and not s > (scalar -0.001)): #in order to avoid false negatives related to the limited precision
break
else:
if n == (len(a) - 1):
print("The two vectors are parallel.")
n = n + 1
def normalize2(a):
if dot(a, a) == 0:
print("The magnitude of this vector is 0 - it is a zero vector and so it has no direction.")
return
return (dot(a, a))**0.5
def find_angle(a, b):
c = dot(a, b)
if c == 0 or c < 0.001 and c > -0.001:#otherwise with just if c == 0 you get a lot of false negatives
print("The two vectors are orthogonal.")
theta = arccos(c/(normalize2(a) * normalize2(b)) )
print(f"The angle, the shorter one, between the two vectors is {theta} radians or {math.degrees(theta)} degrees.")
a = array([-7.5, -7.8])
print(a)
b = array([22.5, 23.4])
print(b)
find_angle(a, b)
oracle(a, b)
a = array([-1.0, -2.0])
print(a)
b = array([2.0, 4.0])
print(b)
find_angle(a, b)
oracle(a, b)
当我运行代码时,我得到以下 output:
[-7.5 -7.8]
[22.5 23.4]
-351.27
The angle, the shorter one, between the two vectors is 3.141592638688632 radians or 179.99999914622634 degrees.
[-1. -2.]
[2. 4.]
-10.0
The angle, the shorter one, between the two vectors is 3.1415926325163688 radians or 179.99999879258172 degrees.
The two vectors are parallel.
我不知道为什么oracle
function 确实以array([-7.5, -7.8])
和array([22.5, 23.4])
不并行的方式运行。 然而,这两个向量显然是平行的。 为什么这样?
您的有限精度逻辑似乎不正确。 s != scalar
将在出现精度问题时返回 True,因为您使用了 or,所以整个检查都为 True。 (也是一种非常复杂的方法)
if s != scalar or (not s < (scalar + 0.001) and not s > (scalar -0.001)):
应该
if abs(scalar-s) > 0.001
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.