python - 为什么我的函数的输出是二进制的?

标签 python numpy matplotlib

我编写了一个可微的 Heaviside 函数并将其矢量化。然而,输出似乎是奇怪的和二进制的。代码如下:

import numpy as np
import matplotlib.pyplot as plt

def heaviside(x, epis):
    if (x>= epis):
        y=1
    elif (x< -epis):
        y=0;
    else:
        y = 0.5 + x/(2*epis) + np.sin(np.pi*x/epis)/(2*np.pi);

    print (x, y);
    return y;

x1 = np.linspace(-1, 1, 100);
vheaviside = np.vectorize(heaviside);
y1 = vheaviside(x1, 0.2);
plt.plot(x1, y1, 'b', alpha=0.3)
plt.show()

输入是 [-1, 1] 中的数组,输出应该是连续的 Heaviside 函数。但是,所有输出都是 01。为什么?

最佳答案

您需要指定何时vectorize它应该使用 floats 的函数:

vheaviside = np.vectorize(heaviside, [float])

否则,根据文档:

The output type is determined by evaluating the first element of the input

在本例中是一个整数。或者,通过替换例如,确保 heaviside 始终返回 float y = 1y = 1.0

关于python - 为什么我的函数的输出是二进制的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30844987/

相关文章:

python - 将 NumPy 数组内容写入 Python 中的文件

python - cython 中 np.int、np.int_、int 和 np.int_t 之间的区别?

python - 使用 numpy 数组调用 lambda

excel - Matplotlib:直接从 .csv 导入并绘制带有图例的多个时间序列

python - 如何删除字符串开头的一定数量的字符

python - Pika basic_publish 在多个队列上发布时挂起

python - 我不知道我的 TensorFlow 程序出了什么问题

python - 用于处理基于计算的请求的 Django 和 REST API

python - 在matplotlib中自动缩写长度字符串

python - 使用 statsmodel 改变无花果大小