Differences

This shows you the differences between two versions of the page.

 — developer:scriptsamples:quadraticsolver [2015/09/14] (current) Line 1: Line 1: + ====== A Quadratic Solver in Script ====== + > **Developer:​** //​[[developer:​rhinoscript|RhinoScript]]//​ + > **Summary:​** //​Demonstrates how to solve quadratic equations in RhinoScript and python.// + + =====Question===== + I am trying to solve quadratic equations, but the results seem incorrect at times. What can I do? + + {{:​legacy:​en:​quad.jpg}} + + =====Answer===== + Most likely, the problem that you are experiencing are floating point rounding errors. Being that you only get 15 decimal places of accuracy, you can use them all up if you are dealing with small numbers. + + The following algorithm should produce more accurate results: + + **RhinoScript** + ​ + Function QuadraticSolver(a,​ b, c) + Dim d, s0, s1 + d = b * b - 4 * a * c + If d < 0 Then + ' No real solution + QuadraticSolver = Null + Else + s0 = (-b - Sqr(d)) / (2 * a) + s1 = (-b + Sqr(d)) / (2 * a) + If Abs(s0) < Abs(s1) Then s0 = s1 + s1 = c / (a * s0) + QuadraticSolver = Array(s0,​s1) + End If + End Function + ​ + + **Python** + ​ + import math + def quadraticsolver(a,​b,​c):​ + d = b * b - 4 * a * c + if d < 0: return # No real solution + + s0 = (-b - math.sqrt(d)) / (2 * a) + s1 = (-b + math.sqrt(d)) / (2 * a) + if abs(s0) < abs(s1): s0 = s1 + s1 = c / (a * s0) + return s0, s1 + ​ + + \\ + + {{tag>​Developer RhinoScript RhinoPython}}
{"found_math": false, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 0, "mathjax_display_tex": 0, "mathjax_asciimath": 0, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 0, "wp-katex-eq": 0, "align": 0, "equation": 0, "x-ck12": 0, "texerror": 0}