Using F# to compute roots from the Quadratic equation

F# is great for creating quick mathematical calculations.  One good use of F# is to compute roots from the quadratic equation.  To get both roots of the quadratic from entered coefficients,  you can create a tuple from the quadratic equation:

let quad (a,b,c) = (((-b + Math.Sqrt((b*b) - (4.0*a*c)))/(2.0*a)), ((-b + Math.Sqrt((b*b) - (4.0*a*c)))/(2.0*a)));;

val quad : float * float * float -> float * float

The result of the equation ax2 + bx + c  for (a =1 , b= 2, and c = 1)  is shown below (in other words the roots for x2 + 2x + 1):

> quad (1.0,2.0,1.0);;

val it : float * float = (-1.0, -1.0)

A little less reduntant F# code could be created by breaking out the sqrt part of the equation and feeding the result back into the quadratic.

> let q (a, b, c) = Math.Sqrt(b*b - 4.0*a*c)
           let quad (a,b,c) = ((-b + q(a,b,c))/(2.0*a), (-b - q(a,b,c))/(2.0*a));;

val q : float * float * float -> float

val quad : float * float * float -> float * float

Note we get the same results:

> quad (1.0,2.0,1.0);;

val it : float * float = (-1.0, -1.0)

We can also try for other coefficients such as  the equation x2 - 4x - 5 where (a=1, b=-4, and c=-5) :

> quad (1.0, -4.0, -5.0);;

val it : float * float = (5.0, -1.0)

After playing in the interactive window for a bit,  I decided to create a real F# project in visual Studio.  I added a new test.fs file to my project

 Then I added the following code to test.fs:

open System;   // open the .NET System library
let q (a, b, c) = Math.Sqrt(b*b - 4.0*a*c)  // create the set of quadratic equations for calculating the root
let quad (a,b,c) = ((-b + q(a,b,c))/(2.0*a), (-b - q(a,b,c))/(2.0*a));;
let v = (quad(1.0, 2.0, 1.0));;   // compute the root of  x2 + 2x + 1
print_string
"The root is ";   // print out the root using the F# print functions
print_any v;
Console.ReadLine()   // prevent the console from closing until enter is hit

The results of running the program are shown below:

More on the printing functions in my next blog....