gpt4 book ai didi

python - Matplotlib 和 Numpy : Log plot with high order numbers

转载 作者:太空宇宙 更新时间:2023-11-03 14:46:38 24 4
gpt4 key购买 nike

我正在尝试使用 Matplotlib 在一个绘图上绘制几个点,该绘图的线条遵循 energy() 中定义的函数。这些点是等 ionic 体参数,线遵循使用多个德拜长度值连接它们的函数。

import matplotlib.pyplot as plt
import numpy as np

n_pts = [10**21,10**19,10**23,10**11,10**15,10**14,10**17,10**6]
KT_pts = [10000,100,1000,0.05,2,0.1,0.2,0.01]

n_set = np.logspace(6,25)
debye_set = 7.43*np.logspace(-1,-7,10)

def energy(n,debye):
return n*(debye/7430)**2

fig,ax=plt.subplots()

ax.scatter(n_pts,KT_pts)

for debye in debye_set:
ax.loglog(n_set,energy(n_set,debye))

plt.show()

这会出现以下错误:

AttributeError: 'int' object has no attribute 'log'

最佳答案

对于大于 64 位整数(在 64 位系统上)所能容纳的整数,Python 会自动执行奇怪的操作,例如 10**21。这样做时,numpy 将不会自动对此类对象使用 numpy dtype,而是使用对象 dtype。反过来,这不支持像 np.log 这样的 ufunc:

> np.log([10**3])
array([ 6.90775528])
> np.log([10**30])
AttributeError: 'int' object has no attribute 'log'

这里一个简单的解决方案是确保 numpy 将 n_pts(包含大数字的数组)转换为它实际可以使用的数据类型,例如 float:

import matplotlib.pyplot as plt
import numpy as np

n_pts = np.array([10**21,10**19,10**23,10**11,10**15,10**14,10**17,10**6], dtype='float')
KT_pts = [10000,100,1000,0.05,2,0.1,0.2,0.01]

n_set = np.logspace(6,25)
debye_set = 7.43*np.logspace(-1,-7,10)

def energy(n,debye):
return n*(debye/7430)**2

fig,ax=plt.subplots()

ax.scatter(n_pts,KT_pts)

for debye in debye_set:
ax.loglog(n_set,energy(n_set,debye))

plt.show()

output

关于python - Matplotlib 和 Numpy : Log plot with high order numbers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46186528/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com