Last active
April 7, 2022 15:45
-
-
Save devcutler/ec9c615f58e961843f6996a3077b5911 to your computer and use it in GitHub Desktop.
Some functions for doing slope calculations that I wrote during my math class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// uses https://github.com/ekg/fraction.js for displaying equation in fraction form | |
var Fraction = require('fractional').Fraction; | |
// returns the slope of a line in either a float or a string representation of a fraction, for reading. | |
// pass in two xy coordinate points and a boolean. | |
// if the boolean is true, it will return the fraction representation, and if false, a float. | |
// the xy coordinate points should be either arrays [x, y] or objects {x: 1, y: 1} | |
function slope(p1, p2, frac) { | |
return frac ? | |
new Fraction(((p2.y || p2[1]) - (p1.y || p1[1])), ((p2.x || p2[0]) - (p1.x || p1[0]))).toString() | |
: | |
((p2.y || p2[1]) - (p1.y || p1[1])) / ((p2.x || p2[0]) - (p1.x || p1[0])) | |
}; | |
// returns the y-intercept of the line. | |
// pass in the slope (m) and an xy coordinate point. | |
function yint(m, p) { | |
return (p.y || p[1]) - (m * (p.x || p[0])) | |
}; | |
// returns the equation of the line in y=mx+b format | |
// until I update this, it takes two xy coordinate points. | |
function equation(p1, p2) { | |
return 'y=' + slope(p1, p2, true) + 'x+' + yint(slope(p1, p2), p1) | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I wrote this in my math class so I didn't have to do the tedious process of figuring out slope and y-int forty times. this is much easier.