Post Reply 
Coding Challenge for Vieta's Formulas
07-21-2018, 01:10 PM (This post was last modified: 07-21-2018 01:47 PM by Namir.)
Post: #10
RE: Coding Challenge for Vieta's Formulas
I found a C++ listing that calculates the polynomial coefficnts, given the roots of that polynomial, using the Vieta's Formulas. I checked the code using Visual Studio 2017 Community Edition. The C++ code had a small error in the range of the nested loop (for j = ...). I corrected it and then translated it into Excel VBA. Here is the version that uses Option Base 1 arrays:

Code:
Option Explicit
Option Base 1

Function Vieta(ByRef A() As Double, ByRef X() As Double, _
               ByRef B() As Double, ByVal N As Integer) As Double
  Dim I As Integer, J As Integer
  Dim Sum As Double, A1 As Double
  
  A1 = A(1)
  For I = 1 To N + 1
    A(I) = A(I) / A1
  Next I

  B(N + 1) = 1
  For I = 1 To N
    For J = N - I To N - 1
      B(J + 1) = B(J + 1) - X(I) * B(J + 2)
    Next J
  Next I
  
  Sum = 0
  For I = 1 To N + 1
    Sum = Sum + (A(I) - B(N + 2 - I)) ^ 2
  Next I
  
  Vieta = Sqr(Sum)
  
End Function

Sub go()
   Dim I As Integer, J As Integer, N As Integer
   Dim A() As Double, B() As Double, X() As Double
   
   Range("B7").Clear
   N = Range("A1").CurrentRegion.Rows.Count - 2
   ReDim A(N + 1), X(N), B(N + 1)

   For I = 1 To N
     A(I) = Cells(I + 1, 1)
     X(I) = Cells(I + 1, 2)
   Next I
   A(N + 1) = Cells(N + 2, 1)
  
   Cells(N + 3, 2) = Vieta(A, X, B, N)
   J = 1
   For I = N + 1 To 1 Step -1
     Cells(J + 1, 3) = B(I)
     J = J + 1
   Next I
End Sub

The above code uses the following spreadsheet columns (the first row has headings and so value appear as of row 2):

1) Column A has the polynomial coefficients with cell A2 being the coefficient of the higher term. There are N + 1 entries in this column.
2 Column B has N roots, starting with cell B2.
3) Column C has the output array B() which should match the values in the first columns if the roots match the polynomial coefficients. The first value appears in cell C2.
4) Cell B7 displays the value of the Vieta's Formula function.

The VBA code is similar to, but not an exact match, to Vallentin's HP-71B code. Note that the values in array B() are in reverse order of the values in array A().
Find all posts by this user
Quote this message in a reply
Post Reply 


Messages In This Thread
RE: Coding Challenge for Vieta's Formulas - Namir - 07-21-2018 01:10 PM



User(s) browsing this thread: 1 Guest(s)