You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Matplotlib绘制极坐标函数异常:Desmos正常显示圆形但Python绘图出错

极坐标绘图异常问题解决

问题描述

我尝试用Matplotlib绘制某极坐标函数,在Desmos应用中该方程可正确显示为圆形,但移植到Python后绘图结果异常。代码如下:

import numpy as np
import matplotlib.pyplot as plt

def fungsi_r4(theta, theta0, r0, a):
  return r0 * np.cos(theta - theta0) + np.sqrt((a ** 2) - (r0 ** 2) * (np.sin(theta - theta0) ** 2))

theta = np.linspace(0, 2 * np.pi, 100)
r = fungsi_r4(theta, 2.4, 5.1, 2.6)

ax = plt.subplot(projection='polar')
ax.plot(theta, r)

我猜测问题与函数返回的负值有关,但不知道该如何处理。

问题分析

  1. 参数导致无效解:你设置的r0=5.1大于a=2.6,此时根号内的表达式a² - r0² sin²(theta-theta0)会在大部分theta取值下为负数,计算结果为复数或NaN,这部分点无法被正确绘制。
  2. 单符号缺失完整解:Desmos能显示完整圆形,是因为它默认处理了方程的正负根号两种情况(r = r0 cos(theta-theta0) ± √(...)),而你的Python代码只取了加号,仅绘制了部分曲线。
  3. 负值的影响:极坐标中r为负值时,Matplotlib会自动将r转为正值,并把theta加上π,这会导致图形偏移变形。

解决方案

修改代码,同时计算正负根号的情况,并处理无效的NaN值:

import numpy as np
import matplotlib.pyplot as plt

def fungsi_r4(theta, theta0, r0, a):
    x = theta - theta0
    sqrt_term = np.sqrt(np.maximum(a**2 - r0**2 * np.sin(x)**2, 0))  # 避免根号内为负,替换为0
    r_plus = r0 * np.cos(x) + sqrt_term
    r_minus = r0 * np.cos(x) - sqrt_term
    return r_plus, r_minus

theta = np.linspace(0, 2 * np.pi, 500)  # 增加采样点,让曲线更平滑
r_plus, r_minus = fungsi_r4(theta, 2.4, 5.1, 2.6)

ax = plt.subplot(projection='polar')
ax.plot(theta, r_plus)
ax.plot(theta, r_minus)
plt.show()

关键修改说明

  • 用np.maximum(..., 0)确保根号内的值非负,避免出现NaN或复数。
  • 同时计算+√和-√两种情况,组合起来得到完整的圆形曲线。
  • 增加theta的采样点数量,让绘制的圆形更平滑。

内容的提问来源于stack exchange,提问作者Fahmi Noor Fiqri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 01:32:39