5 ms·
Hello HN, I was learning JavaScript by completing challenges on CoderByte[0], where one of the hard challenges was to find the point where two lines intersect.
by nicolewhite 11y ago
Hello HN,
I was learning JavaScript by completing challenges on CoderByte[0], where one of the hard challenges was to find the point where two lines intersect. The lines were defined by two sets of points, and you had to return your answers as rationals, not floats. The challenge isn't timed, so I got a little carried away: ended up making a Fraction class, Equation class, etc. This first iteration could only solve linear equations, but I decided to expand it out into a library that could solve higher order polynomials and manipulate expressions.
On a related note, solving cubics is actually kind of hard. This guy Cardano[1] figured it out[2] in the 1500s, but his solution was incomplete because he wasn't aware of imaginary numbers at the time. I then found you could solve cubics with some trig[3] and decided to go that route. Anyway, hope you enjoy, and of course I am interested in your feedback.
[0] http://coderbyte.com/ http://coderbyte.com/
[1] https://en.wikipedia.org/wiki/Gerolamo_Cardano https://en.wikipedia.org/wiki/Gerolamo_Cardano
[2] https://en.wikipedia.org/wiki/Cubic_function#Cardano.27s_method https://en.wikipedia.org/wiki/Cubic_function#Cardano.27s_met...
[3] http://www.nickalls.org/dick/papers/maths/cubic1993.pdf http://www.nickalls.org/dick/papers/maths/cubic1993.pdf
- Gladdyu 11y agoCardanos equation is complete, but only under the assumption that complex numbers exist, however, the same is true for the formula of closed-form solutions of quadratic equations. The difference is that Cardanos equation might make use of complex numbers but in the end, returns a real solution whereas the quadratic solver remains complex whenever D < 0. So in order to implement qubic equations you'd need (a) support for complex numbers, even though the final solution might be real and (b) support for reducing (square and higher order) roots. (b) would be a very valuable addition, as it also allows you to incorporate equations like x^2 - 2 = 0 which solves to x = sqrt(2) or x = -sqrt(2).
- nicolewhite 11y agoYes, thank you for the clarification. Maybe "incomplete" was the wrong word; I was referring to the note on the Wikipedia page: > At this point, Cardano, who did not know complex numbers, supposed that the roots of this equation were real, that is that q^2/4 + p^3/27 > 0. I actually had initial plans to do it Cardano's way: I added a Complex class for the very situation you described[0], but ended up abandoning it as the trig solution seemed more straightforward. [0] https://github.com/nicolewhite/algebra.js/commit/47b6cbba37523da89b0228e050a9ed02e4dcb6a1 https://github.com/nicolewhite/algebra.js/commit/47b6cbba375...