Sympy Simplify eliminate imaginary numbers

帅比萌擦擦* 提交于 2019-12-24 05:31:36

问题


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

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

回答1:


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


来源:https://stackoverflow.com/questions/53421480/sympy-simplify-eliminate-imaginary-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!