0

i am converting a matlab code to python. i found a strange difference of sum of matlab and python. i want to have same output in python like i am getting in matlab. is it possible ? in 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

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
umair ali
  • 1
  • 6
  • You are working with IEEE754 floating-point numbers. You cannot expect absolute accuracy: values will always be approximate. Your Python and Matlab code snippets both return approximately zero. 'Strange' behaviour like this is perfectly normal. – Luke Woodward May 08 '21 at 12:32
  • so which float values i use to get same output in python,,, just like matlab – umair ali May 08 '21 at 12:50
  • if you just run a for loop and sum them up then we can get same results .... but that will be like sum (x) in matlab – umair ali May 08 '21 at 12:58

1 Answers1

0

The difference is not the numeric representation but in the order of summation. You can see this just in 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, e.g., whether the array operation takes advantage of your CPU's vector registers. 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?

bg2b
  • 1,939
  • 2
  • 11
  • 18