Skip to content

Instantly share code, notes, and snippets.

@srifqi
Forked from 140bytes/LICENSE.txt
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save srifqi/fd45f04d43649358abb0 to your computer and use it in GitHub Desktop.
Save srifqi/fd45f04d43649358abb0 to your computer and use it in GitHub Desktop.
Quaratic Formula Solver

140byt.es

A tweet-sized, fork-to-play, community-curated collection of JavaScript.

Quadratic Formula Solver

Quadratic formula

  -b ± Math.sqrt(Math.pow(b,2) - 4*a*c)
  -------------------------------------
                  2*a

Usage

var solve = function(a,b,c){c=Math.sqrt(b*b-4*a*c);return[(c-b)/(2*a),(-b-c)/(2*a)]};
solve(1,2,-8); // returns [2,-4]
/* Quadratic formula
* -b ± Math.sqrt(Math.pow(b,2) - 4*a*c)
* -------------------------------------
* 2*a
*/
/* a, b, c are from equation with format:
* ax^2 + bx + c = 0
*/
function(a,b,c){
/* save the Math.sqrt(Math.pow(b,2) - 4*a*c) in c
* so, the formula being:
* - b ± c
* -------
* 2*a
*/
c=Math.sqrt(b*b-4*a*c);
// note the ± after the b variable
return[
( c-b)/(2*a), // ± -> positive (note that -b+c => c-b)
(-b-c)/(2*a) // ± -> negative
]
};
function(a,b,c){c=Math.sqrt(b*b-4*a*c);return[(c-b)/(2*a),(-b-c)/(2*a)]};
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 Muhammad Rifqi Priyo Susanto srifqi.github.io
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "quadraticFormulaSolver",
"description": "Solve and return the results using quadratic formula",
"keywords": [
"quadratic",
"formula",
"solver",
"math"
]
}
<!DOCTYPE html>
<title>Foo</title>
<div>Expected value: <b>2,-4</b></div>
<div>Actual value: <b id="ret"></b></div>
<script>
// write a small example that shows off the API for your example
// and tests it in one fell swoop.
var myFunction = function(a,b,c){c=Math.sqrt(b*b-4*a*c);return[(c-b)/(2*a),(-b-c)/(2*a)]};
document.getElementById( "ret" ).innerHTML = myFunction(1,2,-8).join();
</script>
@atk
Copy link

atk commented Feb 6, 2015

instead of -b+c, you can write c-b and save one byte.

@srifqi
Copy link
Author

srifqi commented Feb 22, 2015

Thanks, atk!
Never thought that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment