logo  VB.Net - Quadratic and Cubic Roots
This Chapter
Mathematics
Area
Statistics
Factorial
Trignometry
Hyperbolic Trig.
Number Range
Quad&Cubic
Chapters
Home Page
Colours, RGB
Computer Specifications
Dates&Times
Disk Drives
Files
Folders
GPS and OS Ref
VB.Net Forms
Image Files
If & Select
List/Array
Mathematics
NuGet
Sound
String Functions
Sun and Moon
User Controls
Validation
DigitalDan Sites
My Other Sites
Contact Site

Note
Some pages
may contain
inaccuracies
Hits=5
Quadratic Roots

Public Function QuadraticRoots(a As Double, b As Double, c As Double) As List(Of Complex)
 'x = [-b ± √(b2 – 4ac)] /2a
 Dim ret As New List(Of Complex)
 Dim comp As Complex
 Dim bb4ac As Double = (b * b) - (4 * a * c)
 If bb4ac > 0 Then ' real roots
  comp.real = (0 - b + Math.Sqrt(bb4ac)) / (2 * a)
  comp.imaginary = 0
  ret.Add(comp)
  comp.real = (0 - b - Math.Sqrt(bb4ac)) / (2 * a)
  comp.imaginary = 0
  ret.Add(comp)
  Return ret
 End If
 ' if we get here we have complex or imaginary roots
 comp.real = (0 - b) / (2 * a)
 comp.imaginary = 0 + (Math.Sqrt(0 - bb4ac) / (2 * a))
 ret.Add(comp)
 comp.real = (0 - b) / (2 * a)
 comp.imaginary = 0 - (Math.Sqrt(0 - bb4ac) / (2 * a))
 ret.Add(comp)
 Return ret
End Function
Public Structure Complex
    Dim real As Double
    Dim imaginary As Double
End Structure
  
Cubic Roots

Public Function CubicRoots(a As Double, b As Double, c As Double, d As Double) As List(Of Complex)
 Dim ret As New List(Of Complex)
 Dim comp As Complex
 Dim F As Double = ((3 * c) - (b * b)) / 3
 Dim G As Double = ((2 * b * b) - (9 * b * c) + (27 * d)) / 27
 Dim H As Double = (G * G / 4) + (F * F * F / 27)
 ' If H < 0 Then  real roots
 If H < 0 Then
  Dim I As Double = Math.Sqrt((G * G / 4) - H)
  Dim J As Double = Math.Pow(I, (1 / 3))
  Dim K As Double = a * Math.Cos((0 - G) / (2 * I))
  Dim M As Double = Math.Cos(K / 3)
  Dim N As Double = Math.Sqrt(3) * Math.Sin(K / 3)
  Dim P As Double = 0 - (b / 3)
  comp.real = P + (2 * J * M)
  comp.imaginary = 0
  ret.Add(comp)
  comp.real = P - ((J * (M + N)))
  comp.imaginary = 0
  ret.Add(comp)
  comp.real = P - ((J * (M - N)))
  comp.imaginary = 0
  ret.Add(comp)
  Return ret
 End If
 Dim R As Double = ((0 - G) / 2) + Math.Sqrt(H)
 Dim S As Double = Math.Pow(R, (1 / 3))
 Dim T As Double = ((0 - G) / 2) - Math.Sqrt(H)
 Dim U As Double = 0 - Math.Pow(0 - T, (1 / 3))
 comp.real = S + U - (b / 3)
 comp.imaginary = 0
 ret.Add(comp)
 comp.real = 0 - ((S + U) / 2) - (b / 3)
 comp.imaginary = (S - U) * Math.Pow(3, (1 / 3)) / 2
 ret.Add(comp)
 comp.real = 0 - ((S + U) / 2) - (b / 3)
 comp.imaginary = 0 - ((S - U) * Math.Pow(3, (1 / 3)) / 2)
 ret.Add(comp)
 Return ret
End Function
Public Structure Complex
    Dim real As Double
    Dim imaginary As Double
End Structure
  

DigitalDan.co.uk