numpy 如何在指数的底部绘制负值[重复]

fkvaft9z  于 2023-10-19  发布在  其他
关注(0)|答案(1)|浏览(122)

此问题已在此处有答案

NumPy, RuntimeWarning: invalid value encountered in power(2个答案)
上个月关门了。
我想用python绘制f(x) = x^(2/3),但是,我只能让它绘制x的正值。
有人知道我哪里做错了吗?

import numpy as np
import matplotlib.pyplot as plt

# Define the function
def f(x):
    return x ** (2/3)

# Generate x values for both positive and negative x
x_positive = np.linspace(0, 10, 200)
x_negative = np.linspace(-10, 0, 200)

# Calculate corresponding y values for both sets of x values
y_positive = f(x_positive)
y_negative = f(x_negative)

# Plot
plt.figure(figsize=(8, 6))

# Plot for positive x
plt.plot(x_positive, y_positive, label=r'$f(x) = x^{2/3}$', color='blue')

# Plot for negative x
plt.plot(x_negative, y_negative, linestyle='dashed', color='blue')

plt.title('f(x) = x^(2/3)')
plt.xlabel('x')
plt.ylabel('f(x)')
plt.grid(True)
plt.legend()
plt.ylim(-10, 10)  
plt.xlim(-10, 10)  
plt.axhline(y=0, color='black', linewidth=0.8)  # x-axis
plt.axvline(x=0, color='black', linewidth=0.8)  # y-axis
plt.show()

这将导致一个警告和一个x范围为一半的图。

C:\Users\...\AppData\Local\Temp\ipykernel_35264\1241025677.py:3: RuntimeWarning: invalid value encountered in power
  return x ** (2/3)

mmvthczy

mmvthczy1#

在函数f(x)= x^(2/3)的图形中,只有正x值的图形是可见的,因为将负数提高到2/3的幂会导致复数。在二维图形中,复数不能直接绘制。因此,该图只显示了对应于x的真实的值的部分,即正值。但您可以绘制负x值的绝对值并在图中指示负号。

import numpy as np
import matplotlib.pyplot as plt

# Define the function
def f(x):
    return np.power(np.abs(x), 2/3) * np.sign(x) # Here is the change

# Generate x values for both positive and negative x
x_positive = np.linspace(0, 10, 200)
x_negative = np.linspace(-10, 0, 200)

# Calculate corresponding y values for both sets of x values
y_positive = f(x_positive)
y_negative = f(x_negative)

# Plot
plt.figure(figsize=(8, 6))

# Plot for positive x
plt.plot(x_positive, y_positive, label=r'$f(x) = x^{2/3}$', color='blue')

# Plot for negative x
plt.plot(x_negative, y_negative, linestyle='dashed', color='blue')

plt.title('f(x) = x^(2/3)')
plt.xlabel('x')
plt.ylabel('f(x)')
plt.grid(True)
plt.legend()
plt.ylim(-10, 10)  
plt.xlim(-10, 10)  
plt.axhline(y=0, color='black', linewidth=0.8)  # x-axis
plt.axvline(x=0, color='black', linewidth=0.8)  # y-axis
plt.show()

相关问题