绘制函数的对数

问题描述 投票:0回答:2

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

python numpy math matplotlib logarithm
2个回答
2
投票

说 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()


1
投票

如果您的困难在于计算以 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()
函数使用哪个基数并不重要:对于任何基数,您都会得到相同的答案。

© www.soinside.com 2019 - 2024. All rights reserved.