首页 > 解决方案 > Python 中的 Epitrocoid 没有给出正确的情节

问题描述

我在 C# 中编写了以下代码:

using System;
using System.Drawing;
using ZedGraph;

namespace _1_12_Epitrocoid
{
    class Epitrocoid
    {
        double A = 1.0;
        double a = 0.4;
        double λ = 1.4;

        public double X(double ϕ)
        {
            return (A + a) * Math.Cos(ϕ) - λ * a * Math.Cos(((A + a) / a) * ϕ);
        }

        public double Y(double ϕ)
        {
            return (A + a) * Math.Sin(ϕ) - λ * a * Math.Sin(((A + a) / a) * ϕ);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Epitrocoid e = new Epitrocoid();

            PointPairList list = new PointPairList();

            for (double ϕ = 0; ϕ < 10; ϕ += 0.01)
            {
                double x = e.X(ϕ);
                double y = e.Y(ϕ);

                list.Add(x, y);
            }

            PlotForm f = new PlotForm("Epitrocoid");
            f.Add(list, "Epitrocoid", Color.Black);
            f.AxisChange();
            f.ShowDialog();

            Console.ReadLine();
        }
    }
}

在此处输入图像描述

我将此源代码转换为 Python,如下所示:

import math
import matplotlib.pyplot as plt 

A = 1.0;
a = 0.4;
λ = 1.4;

def X(ϕ):
    return (A + a) * math.cos(ϕ) - λ * a * math.cos(((A + a) / a) * ϕ);

def Y(ϕ):
    return (A + a) * math.sin(ϕ) - λ * a * math.sin(((A + a) / a) * ϕ);


x_list = []
y_list = []


for i in range(0, 1001, 1):
    ϕ = i / 1000.0
    x_list.append(X(ϕ))
    y_list.append(Y(ϕ))

print(len(x_list))
print(len(y_list))

plt.plot(x_list, y_list) 

在此处输入图像描述

有人可以告诉我这里出了什么问题吗?

标签: pythonc#matplotlib

解决方案


您在 Python 中构建迭代器的方式(最高 phi = 1)与在 C# 中的构建方式不同(最高 phi = 10)。

使用正确的 phi 可以帮助您使用 Python。此外,使用 numpy 可以大大简化事情。

import numpy
from matplotlib import pyplot

A = 1.0;
a = 0.4;
λ = 1.4;

def X(ϕ):
    return (A + a) * numpy.cos(ϕ) - λ * a * numpy.cos(((A + a) / a) * ϕ);

def Y(ϕ):
    return (A + a) * numpy.sin(ϕ) - λ * a * numpy.sin(((A + a) / a) * ϕ);


ϕ = numpy.arange(0, 10, 0.01)
x = X(ϕ)
y = Y(ϕ)

fig, ax = pyplot.subplots()
ax.plot(x, y)
ax.set_aspect('equal')

在此处输入图像描述


推荐阅读