【问题标题】:Python: Plotting the logarithm of a functionPython:绘制函数的对数
【发布时间】:2017-04-19 03:41:20
【问题描述】:

我有一个可以绘制的函数。 现在我想绘制这个函数的对数。 Python 说 log10() 没有为函数定义(我理解)。 所以问题是:如何绘制像 f(x,a)=a*(x**2) 这样的函数的对数?

【问题讨论】:

  • 您的问题是计算以 10 为底的对数还是绘制值?如果是后者,那与绘制其他任何东西有什么不同?此外,您的 f(x,a) 是两个值的函数。是否要绘制 xs 和常量 a 的变化?
  • x 应该是我的变量,也是我在绘制函数时可以输入的参数。问题是我无法定义正确的函数,例如g(x,a)= log10(f(x,a)) 因为我无法将函数放入日志中。
  • 我的意思是我基​​本上想告诉程序的是:给定 f(x,a)(我已经绘制)在该函数的每个点上使用 log10() 并绘制它
  • 您必须计算值的对数并绘制它们。如果你有,比如说y = f(x, a),并且你已经完成了plot(x, y),你可以做plot(x, np.log10(y))。对于该图,您可能需要一个新图形,或者至少是一组新轴。或者,如果您尝试绘制“对数图”(即具有对数刻度的图),请参阅 matplotlib 绘图函数 semilogy

标签: python numpy math matplotlib logarithm


【解决方案1】:

说 matplotlib 可以绘制函数是一种误导。 Matplotlib 只能绘制值。

所以如果你的功能是

f = lambda x,a : a * x**2

您首先需要为x 创建一个值数组并定义a

a=3.1
x = np.linspace(-6,6)

然后您可以通过绘制数组y = f(x,a)

ax.plot(x,y)

如果您现在想要绘制 f 的对数,您真正需要做的是绘制数组 y 的对数。所以你会创建一个新数组

y2 = np.log10(y)

并绘制它

ax.plot(x,y2)

在某些情况下,与其在线性刻度上显示函数的对数,不如在对数刻度上显示函数本身可能会更好。这可以通过将 matplotlib 中的轴设置为对数并在该对数刻度上绘制初始数组 y 来完成。

ax.set_yscale("log", nonposy='clip')
ax.plot(x,y)

以下是所有三种情况的展示示例:

import matplotlib.pyplot as plt
import numpy as np

#define the function
f = lambda x,a : a * x**2

#set values
a=3.1
x = np.linspace(-6,6)

#calculate the values of the function at the given points
y =  f(x,a)
y2 = np.log10(y)
# y and y2 are now arrays which we can plot

#plot the resulting arrays
fig, ax = plt.subplots(1,3, figsize=(10,3))

ax[0].set_title("plot y = f(x,a)")
ax[0].plot(x,y) # .. "plot f"

ax[1].set_title("plot np.log10(y)")
ax[1].plot(x,y2) # .. "plot logarithm of f"

ax[2].set_title("plot y on log scale")
ax[2].set_yscale("log", nonposy='clip')
ax[2].plot(x,y) # .. "plot f on logarithmic scale"

plt.show()

【讨论】:

    【解决方案2】:

    如果您的困难是计算以 10 为底的对数,请使用

    def g(x, a):
        return math.log(f(x, a)) / math.log(10)
    

    或者只是

    def log10(x):
        return math.log(x) / math.log(10)
    

    这会给非正值带来错误,这正是您想要的。它使用标准标识

    x 底数 b = log(x) / log(b)

    log() 函数使用哪个基数都无关紧要:对于任何基数,您都会得到相同的答案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-24
      • 2019-07-19
      • 1970-01-01
      • 2015-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多