为什么相同的算法在C++和Python中会产生不同的输出?

  • 本文关键字:Python 输出 C++ 算法 python c++
  • 更新时间 :
  • 英文 :


我正在运行一个小代码,其中有周期性边界条件,即,对于点0,左点是最后一个点,对于最后一个点,第零点是右点。当我在Python和c++中运行相同的代码时,我得到的答案是非常不同的。

Python代码

import numpy as np
c= [0.467894,0.5134679,0.5123,0.476489,0.499764,0.564578]
n= len(c)
Δx= 1.0
A= 1.0
M = 1.0
K=1.0
Δt= 0.05
def delf(comp):
ans = 2*A*comp*(1-comp)*(1-2*comp)
return ans
def lap(e,v,w):
laplace = (w -2*v+ e) / (Δx**2)
return laplace
for t in range(1000000):
μ = np.zeros(n)
for i in range(n):
ans1= delf(c[i])

east= i+1
west= i-1

if i==0:
west= i-1+n
if i== (n-1):
east= i+1-n

ans2= lap(c[east], c[i], c[west])

μ[i] = ans1 - K* ans2
dc_dt= np.zeros(n)
for j in range(n):
east= j+1
west= j-1

if j==0:
west= j-1+n
if j== (n-1):
east= j+1-n

ans= lap(μ[east], μ[j], μ[west])

dc_dt[j] = M* ans

for p in range(n):
c[p] = c[p] + Δt * dc_dt[p]
print(c)

Python 3.7.6版本的输出是

[0.5057488166795907, 0.5057488166581386, 0.5057488166452102,
0.5057488166537337, 0.5057488166751858, 0.5057488166881142]

c++代码
#include <iostream>
using namespace std ;
const float dx =1.0;
const float dt =0.05;
const float A= 1.0;
const float M=1.0;
const float K=1.0;
const int n = 6 ;
float delf(float comp){
float answer = 0.0;
answer= 2 * A* comp * (1-comp) * (1-2*comp);
return answer; }
float lap(float e, float v, float w){
float laplacian= 0.0 ;
laplacian = (e - 2*v +w) / (dx *dx);
return laplacian; }
int main(){
float c[n]= {0.467894,0.5134679,0.5123,0.476489,0.499764,0.564578};

for(int t=0; t<50;++t){

float mu[n];
for(int k=0; k<n; ++k){
int east, west =0 ;
float ans1,ans2 = 0;

ans1= delf(c[k]);

if (k ==0){ west = k-1+n; }
else{ west = k-1; }

if (k== (n-1)) { east = k+1-n;  }
else{ east= k+1; }

ans2= lap(c[east], c[k], c[west]);

mu[k] = ans1 - K*ans2; 
}

float dc_dt[n];
for(int p=0; p<n; ++p){
float ans3= 0;
int east, west =0 ;

if (p ==0){ west = p-1+n; }
else{ west = p-1;}

if (p== (n-1)) { east = p+1-n; }
else{ east= p+1; }

ans3= lap(mu[east], mu[p], mu[west]);

dc_dt[p] = M* ans3;
}
for(int q=0; q<n; ++q){         
c[q] = c[q] + dt* dc_dt[q]; 
}             
}
for(int i=0; i<n; ++i){
cout<< c[i]<< " ";
}            
return 0;  
}

c++的输出是

0.506677 0.504968 0.50404 0.50482 0.506528 0.507457

当我迭代小步时,比如t<1000,输出没有显著差异,但我应该为大量迭代(以10^7的顺序)做这个计算,这里输出的差异非常大。

我拿了你的代码,添加了缺少的大"for"循环并将长度从"50"1000000";

然后我把所有的"float"与"double"结果输出为:

0.505749 0.505749 0.505749 0.505749 0.505749 0.505749

因此,当然,在python和c++中实现相同的代码会得到相同的结果。然而,类型显然很重要。例如,在python3中,整数的实现方式与c++或几乎任何其他语言都非常不同。但这里要简单得多。Python3"float"是"双"字。在c++中定义。见https://docs.python.org/3/library/stdtypes.html有趣的事实

在c++或大多数其他语言中重现最简单的python程序是像

这样的程序。
myInt=10000000000000000000000000000000345365753523466666
myInt = myInt*13 + 1
print (myInt)

,因为python可以处理任意大整数(直到您的整个计算机内存被填满)。相应的

#include <iostream>
int main(){ 
long int myInt = 10000000000000000000000000000000345365753523466666;
myInt = myInt*13 + 1;
std::cout << myInt << std::endl;
return 0;
}

将简单地报告警告:整型常量对于其类型来说太大了并且会溢出并打印错误的结果。

最新更新