Sympy Simplify消除虚数 [英] Sympy Simplify eliminate imaginary numbers

查看:497
本文介绍了Sympy Simplify消除虚数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图获得卷积向量之间的余弦相似度.因为我使用的是快速傅立叶变换,所以我使用的是复数.在计算余弦相似度时,返回的最终值应为实数.但是,我的输出包括虚部:1.0*(-1.53283653303955 + 6.08703605256546e-17*I)/(sqrt(5.69974497311137 + 5.55111512312578e-17*I)*sqrt(14.2393958011541 - 3.46944695195361e-18*I))

I'm trying to get the cosine similarity between convolved vectors. Because I'm using fast fourier transform, I am using complex numbers. In the calculation of the cosine similarity, the final value returned should be a real number. However, my output is including imaginary parts: 1.0*(-1.53283653303955 + 6.08703605256546e-17*I)/(sqrt(5.69974497311137 + 5.55111512312578e-17*I)*sqrt(14.2393958011541 - 3.46944695195361e-18*I))

虚部应该为零(它们实际上是零),但是我无法通过sympy将虚部设置为零,这样我就可以得到一个真实值作为输出.

The imaginary portions should be zero (which they effectively are), but I can't get sympy to set the imaginary portions to zero so that I can get a real value as my output.

我已经包含了导致输出的代码.我已经尽力减少了.

I've included the code that leads to the output. It's as pared down as I can accomplish.

# import statements
from sympy import *
from numpy import dot,array,random

# sympy initialization
a, b, c, d, e, f, g, h, i, j, k, l = symbols('a b c d e f g h i j k l')

# vector initialization
alpha = [a, b, c, d];
beta = [e, f, g, h];
gamma = [i, j, k, l];

# discrete fourier initialization (dft/idft)
W = [[1, 1, 1, 1], [1, -1j, -1, 1j], [1, -1, 1, -1], [1, 1j, -1, -1j]];
WH = [[1, 1, 1, 1], [1, 1j, -1, -1j], [1, -1, 1, -1], [1, -1j, -1, 1j]];

# i/fft initialization, cosine similarity
def fft(a):
    return dot(a,W)
def ifft(a):
    return dot(a,WH)/4.0
def cosineSimilarity(a,b):
    return dot(a,b)/(sqrt(dot(a,a)) * sqrt(dot(b,b)))

# x&y initialization
x = ifft(fft(alpha)*fft(beta)) + ifft(fft(alpha)*fft(gamma));
y = ifft(fft(alpha)*fft(beta)/fft(gamma)) +             
ifft(fft(alpha)*fft(gamma)/fft(beta));

# determine cosine similarity between x&y
random.seed(39843)
current = random.rand(12)
mymap = list(zip(params,current))
print(simplify(diff(cosineSimilarity(x, y), a).subs(mymap)))

推荐答案

如果您知道虚部为0,则可以只接受评估的实部,否则使用"chop = True ",请谨慎丢弃相对较小的虚构部分:

If you know the imaginary part is 0 then you can just take the real part of the evaluation, else use "chop=True" with caution to discard relatively small imaginary parts:

>>> q
(-1.53283653303955 + 6.08703605256546e-17*I)/(sqrt(5.69974497311137 + 
5.55111512312578e-17*I)*sqrt(14.2393958011541 - 3.46944695195361e-18*I))
>>> q.n(chop=True)
-0.170146237401735
>>> re(q.n())
-0.170146237401735

这篇关于Sympy Simplify消除虚数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆