2014-09-21 79 views
0

所以我对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() 
+2

尝试一个函数有四个参数,而不是与每一个论辩的四个*嵌套*功能https://docs.python.org/2.7/tutorial/controlflow.html#defining-functions – wwii 2014-09-21 03:04:55

回答

6

斜率功能可以像下面这样 - 一个功能以代表这两个点的四个坐标四个参数:

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

但很明显,它不应该是这个简单,你必须细化它并考虑x1 == x2的情况。

+3

的约定是。通常是'(y2 - y1)/(x2 - x1)'#nitpicking – 2014-09-21 03:18:10

+2

这并不重要,两点是对称的,因为斜率是一个标量而不是矢量。只要你有相同的分子和分母的顺序,就是对的。但是,如果你切换它们,并且有(y2-y1)/(x1-x2)这样的东西 - 那就错了。 – 2014-09-21 03:21:28

0

坡度=上升/运行。这是一个非常简单的解决方案: - 用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() 
0

如果你想从两个数组猜测最适合的斜率,这是最教科书的答案,如果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)) 
相关问题