[英]can i get exactly same sum output in python like matlab
i am converting a matlab code to python.我正在将 matlab 代码转换为 python。 i found a strange difference of sum of matlab and python.我发现 matlab 和 python 的总和有一个奇怪的差异。 i want to have same output in python like i am getting in matlab.我想在 python 中拥有相同的 output,就像我在 matlab 中一样。 is it possible?可能吗? in matlab在 matlab
x = [-200:200]/200; % 401 values from -200 to 200 y =sum(x) y = 9.9920e-16
but in python using different modules i get answer但是在 python 中使用不同的模块我得到了答案
x = np.arange(-200,201)/200 # 401 values from -200 to 200 y = np.sum(x) y = 1.4210854715202004e-14 z = sum(x) z = -8.43769498715119e-15 zmath = math.fsum(x) zmath = 0.0
The difference is not the numeric representation but in the order of summation.区别不是数字表示,而是求和的顺序。 You can see this just in Matlab:您可以在 Matlab 中看到这一点:
>> sum(x(randperm(401)))
ans =
2.7756e-16
>> sum(x(randperm(401)))
ans =
5.8842e-15
>> sum(x(randperm(401)))
ans =
-2.2204e-15
The order of summation is going to depend on implementation details, eg, whether the array operation takes advantage of your CPU's vector registers.求和的顺序将取决于实现细节,例如,数组操作是否利用了 CPU 的向量寄存器。 If you must have exactly the same result, you'll have to write an explicit loop.如果您必须得到完全相同的结果,则必须编写一个显式循环。 (Based on the answers you got, z = sum(x)
in Python is doing that internally.) For more understanding of why this happens, see Why does changing the sum order returns a different result? (根据您得到的答案,Python 中的z = sum(x)
正在内部执行此操作。)要进一步了解为什么会发生这种情况,请参阅为什么更改总和顺序会返回不同的结果?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.