runy977
runy977

Reputation: 13

Python program that tells you the slope of a line

So I am new to python, but have successfully created programs that can calculate area,volume,convert Celsius to Fahrenheit, etc... however, I seem to be having some trouble with this 'slope of a line' program.

# 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()

Upvotes: 1

Views: 15957

Answers (3)

billmanH
billmanH

Reputation: 1426

If you want to guess the best fit slope from two arrays this is the most textbook answer if X and Y are arrays:

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))

Upvotes: 0

Peter Pei Guo
Peter Pei Guo

Reputation: 7870

The slope function could be something like the following - a function taking four parameters representing the four coordinates of those two points:

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

But obviously it should not be this simple, you have to refine it and consider the situation that x1 == x2.

Upvotes: 8

trn450
trn450

Reputation: 341

Slope = rise / run. Here is a very simple solution: - Create a class Point with x and y members. - Create a method getSlope which takes two points as arguments - Instantiate two point variables with their x and y coordinates. - Print the result (which in this case is the return value of the getSlope method.

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()

Upvotes: 0

Related Questions