Python程序,告诉您lin的斜率

2024-05-07 14:16:33 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我是python新手,但已经成功地创建了一些程序,可以计算面积、体积、将摄氏度转换为华氏度等等。。。不过,我似乎对这个“直线斜率”程序有些问题。

# A simple program which prompts the user for two points 
# and then computes and prints the corresponding slope of a line.

# slope(S): (R*R)*(R*R) -> R
# If R*R is a pair of real numbers corresponding to a point,
# then slope(S) is the slope of a line.
def x1(A):
    def y1(B):
        def x2(C):
            def y2(D):
                def slope(S):
                    return (D-B)/(C-A)

# main
# Prompts the user for a pair of points, and then computes
# and prints the corresponding slope of the line.

def main():
    A = eval(input("Enter the value of x1:"))
    B = eval(input("Enter the value of y1:"))
    C = eval(input("Enter the value of x2:"))
    D = eval(input("Enter the value of y2:"))
    S = slope(S)
    print("The slope of a line created with those points\
 is: {}{:.2f}".format(S,A,B,C,D))

main()

Tags: andoftheinputisvaluemaindef
3条回答

如果你想从两个数组中猜出最合适的斜率,这是最经典的答案,如果X和Y是数组:

import numpy as np
from __future__ import division

x = np.array([1,2,3,4]
y = np.array([1,2,3,4])
slope = ((len(x)*sum(x*y)) - (sum(x)*sum(y)))/(len(x)*(sum(x**2))-(sum(x)**2))

slope函数可以是如下所示的函数-一个包含四个参数的函数,表示这两个点的四个坐标:

def slope(x1, y1, x2, y2):
    return (y1 - y2) / (x1 - x2)

但显然不应该这么简单,您必须改进它并考虑x1==x2的情况。

坡度=上升/下降。下面是一个非常简单的解决方案: -使用x和y成员创建类点。 -创建一个方法getSlope,该方法以两点作为参数 -用x和y坐标实例化两个点变量。 -打印结果(在本例中是getSlope方法的返回值)。

class Point:
    def __init__ (self, x, y):
        self.x = x
        self.y = y

# This could be simplified; more verbose for readability    
def getSlope(pointA, pointB):
    rise = float(pointA.y) - float(pointB.y)
    run = float(pointA.x) - float(pointB.x)
    slope = rise/run

    return slope


def main():
    p1 = Point(4.0, 2.0)
    p2 = Point(12.0, 14.0)

    print getSlope(p1, p2)

    return 0

if __name__ == '__main__':
    main()

相关问题 更多 >