Skip to content

Instantly share code, notes, and snippets.

@masyukun
Created May 24, 2015 17:50
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 masyukun/dca03e3c817b59f7a6ab to your computer and use it in GitHub Desktop.
Save masyukun/dca03e3c817b59f7a6ab to your computer and use it in GitHub Desktop.
Solve a cubic polynomial for x, given coefficients a, b, c, d in standard form = ax^3 - bx^2 + cx - d = 0. Uses homegrown cubic root function sqrt3() because Xquery's math library cannot raise a negative number to a decimal power. http://www.math.vanderbilt.edu/~schectex/courses/cubic/
declare function local:solveCubicEquation($a as xs:double, $b as xs:double, $c as xs:double, $d as xs:double) {
let $big := ((-math:pow($b,3.0)) div (27.0 * math:pow($a,3.0))) + (($b * $c) div (6.0 * math:pow($a,2.0))) - ($d div (2.0 * $a))
let $small := ($c div (3.0 * $a)) - (math:pow($b,2.0) div (9.0 * math:pow($a,2.0)))
let $tail := ($b div (3.0 * $a))
let $x := math:pow($big + math:sqrt(math:pow($big,2.0) + math:pow($small,3.0)), (1.0 div 3.0)) + local:sqrt3( $big - math:sqrt(math:pow($big,2.0) + math:pow($small,3.0)) ) - $tail
return $x
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment