Skip to content
Advertisement

Why does the same algorithm result in different outputs in C++ & Python?

I am running a small code in which there are periodic boundary conditions i.e.,for point 0 the left point is the last point and for the last point zeroth point is the right point. When I run the same code in Python and C++, the answer I am getting is very different.

Python Code

JavaScript

The output in Python 3.7.6 version is

JavaScript

C++ Code

JavaScript

Output in C++ is

JavaScript

When I am iterating for small steps say t<1000 there is no significant difference in outputs but I am supposed to do this calculation for large number of iterations (in order of 10^7) and here the difference in output is very large.

Advertisement

Answer

I took your code, added the missing closing bracket of the large “for” loop and also changed the length from “50” to “1000000” as in the python version.

Then I replaced all “float” with “double” and the resulting output is:

0.505749 0.505749 0.505749 0.505749 0.505749 0.505749

Thus, of course, implementing the same code in python and in c++ gives the same result. However, the types are obviously important. For example, integers are implemented in a very very different way in python3 than in c++ or almost any other language. But here it is much simpler. Python3 “float” is a “double” in c++ by definition. See https://docs.python.org/3/library/stdtypes.html

Fun fact

the simplest python program that you will have major trouble to reproduce in C++ or most other languages is something like

JavaScript

since python can work with arbitrary large integers (until your entire computer memory is filled). The corresponding

JavaScript

will simply report warning: integer constant is too large for its type and will overflow and print a wrong result.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement