【问题标题】:Why does NumPy.exp show a different result than exp in C为什么 NumPy.exp 显示的结果与 C 中的 exp 不同
【发布时间】:2017-01-05 07:12:32
【问题描述】:

我正在将一些 Python 代码转换为 C 代码。

下面的 Python NumPy exp 对复数输出 (6.12323399574e-17-1j)k=1l=4

numpy.exp(-2.0*1j*np.pi*k/l)

我将其转换为 C 代码,如下所示。但是输出是1.000000

#include <complex.h>
#define PI 3.1415926535897932384626434
exp(-2.0*I*PI*k/l)

我错过了什么?

【问题讨论】:

  • 你应该在 C 版本中使用cexp(),不是吗?
  • exp 是什么?您使用的是 C++ 还是 tgmath.h? C 中的exp 函数通常不接受复数。无论如何,您如何检查结果?向我们展示可运行的代码。
  • 我认为一旦你将exp 切换到cexp,numpy 和 c 都会产生相同的答案。正确答案是-1i。当您假设 6e-17 真的为零时,这就是 numpy 的真正含义。

标签: python c numpy exponent


【解决方案1】:

您必须使用cimagcreal 来打印数据。

C 版:

#include <stdio.h>
#include <complex.h>
#include <tgmath.h>


int main(){
    int k=1;
    int l=4;
    double PI = acos(-1);
    double complex z = exp(-2.0*I*PI*k/l);
    printf(" %.1f%+.1fj\n", creal(z), cimag(z));
    return 0;
}

输出:

0.0-1.0j

Python 版本:

import numpy as np

k=1
l=4
z = np.exp(-2.0*1j*np.pi*k/l)
print(z)

输出:

6.12323399574e-17-1j

【讨论】:

    【解决方案2】:

    这是打印出你的答案的正确 C 代码:

        x = cexp(-2.0*I*PI*0.25);
        printf("%f + i%f\n", creal(x), cimag(x));
    

    【讨论】:

      猜你喜欢
      • 2020-11-14
      • 2016-11-18
      • 1970-01-01
      • 1970-01-01
      • 2023-01-17
      • 1970-01-01
      • 1970-01-01
      • 2018-04-25
      • 1970-01-01
      相关资源
      最近更新 更多