【问题标题】:Finding the zeroes of a position vector寻找位置向量的零点
【发布时间】:2020-01-27 20:52:45
【问题描述】:

在我的动力学课程中,我的任务是编写一个 Python 代码,该代码将绘制一个位置矢量从它从地面开始到降落到地面的轨迹。我目前让我的代码从我手动计算的两个零值创建一个线性空间,但我想把它编码进去。因为我还需要在轨迹上创建速度向量,所以我将位置向量分解为它的 x 和y 组件。我研究了xlimthis 线程,但不知道如何实现它们。总的来说,我对 python 和编码还很陌生,所以我仍在努力了解事情是如何工作的。

import numpy as np
import matplotlib.pyplot as plt


#creates a function that returns the x component
def re10(x):
    r1 =  0.05*x
    return r1

#creates a function that returns the y component
def re20(x):
    r2 =  -4.91*(x**2) + 30*x + 100
    return r2


#Calculates the two zeroes of the trajectory
tmin = (-30 + np.sqrt(30**2 -4*-4.91*100))/(2*-4.91)
tmax = (-30 - np.sqrt(30**2 -4*-4.91*100))/(2*-4.91)


#Initializing time space
t = np.linspace(tmin, tmax, 100)


#Plot
plt.plot(re10(t), re20(t)) #(x, y)

【问题讨论】:

  • 你为什么不使用simpy? Python 和符号方程一起使用时真的很强大!
  • 我从未听说过 simpy。
  • 给我几秒钟 :)
  • 我的错误,您可以使用numpy 来查找方程式的零点,而您实际上已经根据您的代码找到了它,所以只需使用 np.roots 来查找您的零点!
  • 一些未经要求的编码建议:我强烈建议您在代码中避免使用magic numbers。例如,将g=9.81 放在顶部某处,然后在需要时使用0.5*g 而不是4.91。在编写代码一段时间后阅读代码时,这将大大帮助您(和其他人)。

标签: python


【解决方案1】:

您可以使用numpy 库轻松找到函数的零点。

首先,安装它。打开 cmd 控制台并写入 pip install numpy。 然后,在你的脚本中写下这段代码:

import numpy
re20 = [-4.91, 30, 100]
zeroes = numpy.roots(coeff)
print(zeroes[0])
print(zeroes[1])

正如您在从控制台(或您的 IDE)运行脚本时所看到的,numpy.roots(function) 会将函数的零作为数组返回给您。 这就是为什么您使用[] 运算符来访问它们中的每一个(请注意,在编程中,数组的第一个元素将位于索引0)。

要直接在你的代码中使用它,你可以这样做:

tmin = zeroes[0]
tmax = zeroes[1]

Simpy 用于符号操作,它非常强大,但你不需要它,我的错。

希望您喜欢 Python,它是一门很酷的语言!

【讨论】:

    猜你喜欢
    • 2011-05-04
    • 1970-01-01
    • 2020-10-02
    • 1970-01-01
    • 2021-08-25
    • 1970-01-01
    • 2011-11-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多