繁体   English   中英

python abs函数中的数学计算

[英]Mathematical calculation in python abs function

我正在尝试在 python 中创建方程。 如果这已经被问到,请提前抱歉! 如果是这样,我找不到它,所以请分享帖子!

我遇到了一个问题,我不知道如何对红色方块中的部分进行编码(参见方程式方程 )。 据我了解,“|u1|” 表示 u1 的绝对值。 但是,如果我像写方程一样编码它,即 abs(u1)abs(u2) 我得到一个语法错误(我有点预期)。

我的问题是代码行:

angle = np.arccos((Mu1*Mu2)/(abs(Mu1)abs(Mu2)))

我的完整代码是:

import numpy as np
from math import sqrt 

#first direction vector

#punt 1, PQ
#   [x,y]
P = (1,1)
Q = (5,3)

#punt 2, RS
R = (2,3)
S = (4,1)

#direction vector = arctan(yq-yp/xq-xp)

#create function to calc direction vector of line
def dirvec(coord1, coord2):
    #pull coordinates into x and y variables
    x1 , y1 = coord1[0], coord1[1]
    x2 , y2 = coord2[0], coord2[1]
    #calc vector see article
    v = np.arctan((y2-y1)/(x2-x1))
    #outputs in radians, not degrees
    v = np.degrees(v)
    return v

print(dirvec(P,Q))
print(dirvec(R,S))

Mu1 = dirvec(P,Q)
Mu2 = dirvec(R,S)

angle = np.arccos((Mu1*Mu2)/(abs(Mu1)abs(Mu2)))

print(angle)

我试过的薄:

  • 将两个 abs 相乘,但是我每次都会得到相同的数字 (pi): np.arccos((Mu1*Mu2)/(abs(Mu1)*abs(Mu2)))
  • +-但我无法想象这些是正确的: np.arccos((Mu1 Mu2)/(abs(Mu1)+abs(Mu2))) np.arccos((Mu1 Mu2)/(abs(Mu1)-abs(Mu2) )))

式中,分子为两个向量点积,分母为两个向量的范数之积。

这是编写公式的简单方法:

import math

def dot_product(u, v):
  (x1, y1) = u
  (x2, y2) = v
  return x1 * x2 + y1 * y2

def norm(u):
  (x, y) = u
  return math.sqrt(x * x + y * y)

def get_angle(u, v):
  return math.acos( dot_product(u,v) / (norm(u) * norm(v)) )

def make_vector(p, q):
  (x1, y1) = p
  (x2, y2) = q
  return (x2 - x1, y2 - y1)

#first direction vector

#punt 1, PQ
#   [x,y]
P = (1,1)
Q = (5,3)

#punt 2, RS
R = (2,3)
S = (4,1)

angle = get_angle(make_vector(p,q), make_vector(r,s))

print(angle)

从我看来,您的代码的结果将始终为 pi 或 0。如果 mu1 或 mu2 之一为负,则为 pi,而当两者均为负或正时,它将为零。 如果我正确地记住向量:给定两个向量 P 和 Q,比如说 P = (x, y) 和 Q = (a, b) 然后 abs(P) = sqrt(x^2 + y^2) 和 P. Q = xa+yb。 所以 cos@ = P.Q/(abs(P) *abs(Q))。 如果不清楚,您可以举例说明您打算做什么

好吧,显然我的解释有误。

我要感谢大家的解决方案!

经过一番折腾,看来:

 import math import numpy as np #punt 1, PQ # [x,y] P = (1,1) Q = (5,3) x1 = P[0] x2 = Q[0] y1 = P[1] y2 = Q[1] #punt 2, RS R = (0,2) S = (4,1) x3 = R[0] x4 = S[0] y3 = R[1] y4 = S[1] angle = np.arccos(((x2 - x1) * (x4 - x3) + (y2 - y1) * (y4 - y3)) / (math.sqrt((x2 - x1)**2 + (y2 - y1)**2) * math.sqrt((x4 - x3)**2 + (y4 - y3)**2))) print(angle)

是计算两个向量之间角度的正确方法。 这显然不是漂亮的代码,但它是其工作原理的精髓!

再次感谢大家的反应和解决方案!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM