简体   繁体   English

我能像 matlab 一样在 python 中得到完全相同的总和 output

[英]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.

相关问题 我将带有浮点值的列表格式更改为PYTHON中的元组序列。 但是我得到的输出并不完全相同 - I change the format of a list with floating values to sequence of tuples in PYTHON. But the output i get is not exactly the same 如何在 MATLAB 和 Python 中获得相同的 fft2() 结果? - How can I get same results for fft2() in MATLAB and Python? 如何在R和Python中获得相同格式的输出表? - How can I get the same format of output tables in R and Python? 如何在python中的一个for循环的元组output中获取相同position的总和? - How to get the sum of the same position in a tuple output of a for loop in python? 有没有办法让 python 命令在午夜准确发送? - Is there a way that I can make a python command get sent at exactly midnight? 我如何在python中实现像matlab这样的结构数组? - How can i implement structure array like matlab in python? 我可以将python配置为具有类似于打印的matlab吗? - Can I configure python to have matlab like print? 我如何在python中准确获得2位小数 - How can i get exactly 2 decimal position in python 如何在 python 中准确获取 lambda 函数的代码? - How can I get exactly the code of a lambda function in python? 如何使用 python output 作为 matlab 输入? - How can I use a python output as a matlab input?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM