Solving cubic and quartic equations with Excel

Although in earlier posts (such as this one) I have referred to some User Defined Functions (UDFs)  for solving cubic and quartic equations, I just realised recently that I haven’t actually talked about them here, and since they are in most cases the most practical way of dealing with these equations, that ought to be fixed.

An “on sheet” solution to quadratic, cubic and quartic equations can be found in the spreadsheet Polynom.xls by Alex Tomanovich, which can be downloaded from the ExcelCalcs site.

Polynom.xls Cubic solution

The solutions in polynom.xls provide an excellent explanation of the method of solution, but are not very flexible or practical for solving a large number of equations.  For that purpose I have written four UDFs:

  • Quartic
  • CubicC
  • Cubic
  • Quadratic

Each function, other than Cubic, returns the real and complex roots of a polynomial equation with coefficients specified in either a single column range or a single row range.  Cubic is for use when only the real roots are required, and is a little faster than CubicC.  The functions may either return a single specified root of the equation, or if entered as an array function, will provide all roots (including real and imaginary parts for complex roots) and the number of real and complex roots.  The spreadsheet may be downloaded from Polynomial.zip (including full open source code).  The screenshot below shows input and output:

Quartic.xls input and output, click for full size view

The cubic and quartic functions are based on Fortran code from The homepage of AK Kraska.

Posted in Excel, Maths, Newton, UDFs, VBA | Tagged , , , , , | 24 Comments

The hole through the middle of the Earth – moved to the Equator

Previous posts in this series assumed that the hole went from pole to pole, and ignored such complications as tidal effects and wobbles of the axis of rotation.  In this post we will examine the effect of moving the hole to the equatorial plane, so the ends of the hole (and anything dropped down them) have a significant velocity with respect to the centre.  The up-dated spreadsheet (including full open source code) may be downloaded from ODE-Buckle.zip.

But first, where can we place the ends of the hole?  There are actually very few suitable locations with land close to sea level at both ends.  The location I have chosen is shown below, with ends on the coast of Ecuador, and close to the West coast of Sumatra (found with the aid of antipodemap.com):

Ends of the Earth - at the Equator

The ODE to be solved in this case is shown below.  It is very similar to ODEFunc4 (for a hole along the Polar Axis) , except the position, velocity and acceleration values are now each split into X and Y components, with X being along a line through the centre of the Earth on a non-rotating axis, and Y being distance in the perpendicular direction, on the Equatorial plane. 

ODE for hole through the centre of the Earth on the Equatorial plane

  The Y offset and acceleration in the Y direction are initially set to zero.  In order to check the output the Y velocity was set to orbital velocity.  The output results show a path following the surface of the Earth exactly, indicating that the ODE solution to the problem is providing accurate results:

Input and Output for a body released at the surface with orbital velocity

Plot of orbital velocity results

Finally the initial Y velocity was set to the surface of the Earth (463 m/s), modelling the situation when an object is dropped into a vertical hole at the Equator, with no horizontal velocity, relative to the Earth’s surface.  The results are shown below.  The blue line shows the path that would be followed if the object was unconstrained, and the green line the path followed if the object was constrained by the frictionless sides of a rotating hole.

Path for object dropped with zero velocity relative to the Earth's surface.

Posted in Differential Equations, Excel, Maths, Newton, UDFs, VBA | Tagged , , , , , | 2 Comments

Code Generator

One of the difficulties with Excel routines to solve differential equations, or do numerical integration, is that the equations to be solved must either be coded as VBA functions (which is time consuming), or solved using the evaluate function (which is slow and limited).  An alternative is to automatically generate the VBA function, using data on the spreadsheet; a process which can easily be fully automated so that it only requires the entry of the function to be solved in a suitable text format.  The code generation process is not difficult, but strangely there is little written about it.  The best source of information I have found is Chip Pearson’s site, where he provides detailed instructions, and many detailed examples.  In this post I will describe the essentials to get the process working, and provide a working example (with open source code).  Refer to Chip’s site for more details, and lots more open source code.

A setting  in the Visual Basic Editor (VBE), and an Excel option need to be changed to allow the code generation routines to work:

  • In the VBE choose Tools-References and select the Microsoft Visual Basic For Applications Extensibility 5.3 check box.
  •  From the spreadsheet, select the “Trust access to the VBA project object model” check box.  This is under the Developer Tab (macro security) in Excel 2007 and 2010, and under Tools-Macros-Security in 2003 and earlier versions.

Having done that, the code shown below should work.  I have adapted four procedures from Chip’s site:

  • Sub AddProcedureToModule()
  • Sub DeleteProcedure(ModName As String, ProcName As String)
  • Sub AddModuleToProject(ModName As String)
  • Function VBComponentExists(VBCompName As String, Optional VBProj As VBIDE.VBProject = Nothing) As Boolean

The basic is procedure is:

  • Prompt for a selected spreadsheet range containing the code module name, procedure name, and procedure code.
  • If the code module does not exist, create it.
  • If the procedure already exists, delete it
  • (Re)create the code
Sub AddProcedureToModule()
  Dim VBProj As VBIDE.VBProject
  Dim VBComp As VBIDE.VBComponent
  Dim CodeMod As VBIDE.CodeModule
  Dim LineNum As Long, CLine As Long
  Dim CodeRange As Variant, i As Long, ModName As String, ProcName As String
  Dim DefaultRange As String

    If Selection.Rows.Count > 1 Then
  DefaultRange = Selection.Address
    End If
    On Error GoTo Cancelled
  Set CodeRange = Application.InputBox _
  (Prompt:="Code range:", Title:="Select code range", Default:=DefaultRange, Type:=8)

  CodeRange = CodeRange.Value

  ModName = CodeRange(1, 1)
  ProcName = CodeRange(2, 1)

  If VBComponentExists(ModName) = False Then
  AddModuleToProject ModName
    End If

  Set VBProj = ActiveWorkbook.VBProject
  Set VBComp = VBProj.VBComponents(ModName)
  Set CodeMod = VBComp.CodeModule

  With CodeMod
        On Error Resume Next
  If .ProcCountLines(ProcName, vbext_pk_Proc) > 0 Then
  DeleteProcedure ModName, ProcName
        End If

  LineNum = .CountOfLines + 1
  For i = 1 To UBound(CodeRange) - 2
  CLine = LineNum + i
  .InsertLines CLine, CodeRange(i + 2, 1)
  Next i
    End With
Cancelled:
End Sub

 

Sub AddModuleToProject(ModName As String)
  Dim VBProj As VBIDE.VBProject
  Dim VBComp As VBIDE.VBComponent

  Set VBProj = ActiveWorkbook.VBProject
  Set VBComp = VBProj.VBComponents.Add(vbext_ct_StdModule)
  VBComp.Name = ModName
End Sub

 

Sub DeleteProcedure(ModName As String, ProcName As String)
  Dim VBProj As VBIDE.VBProject
  Dim VBComp As VBIDE.VBComponent
  Dim CodeMod As VBIDE.CodeModule
  Dim StartLine As Long, NumLines As Long
  Dim CodeRange As Variant, i As Long

  CodeRange = Range("coderange").Value
  ModName = CodeRange(1, 1)
  If VBComponentExists(ModName) = False Then
        Exit Sub
    End If

  Set VBProj = ActiveWorkbook.VBProject
  Set VBComp = VBProj.VBComponents(ModName)
  Set CodeMod = VBComp.CodeModule

  With CodeMod

  StartLine = .ProcStartLine(ProcName, vbext_pk_Proc)
  NumLines = .ProcCountLines(ProcName, vbext_pk_Proc)
  .DeleteLines StartLine:=StartLine, Count:=NumLines
    End With

End Sub

 

Public Function VBComponentExists(VBCompName As String, Optional VBProj As VBIDE.VBProject = Nothing) As Boolean
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' This returns True or False indicating whether a VBComponent named
' VBCompName exists in the VBProject referenced by VBProj. If VBProj
' is omitted, the VBProject of the ActiveWorkbook is used.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
  Dim VBP As VBIDE.VBProject
  If VBProj Is Nothing Then
  Set VBP = ActiveWorkbook.VBProject
    Else
  Set VBP = VBProj
    End If
    On Error Resume Next
  VBComponentExists = CBool(Len(VBP.VBComponents(VBCompName).Name))

End Function

The screenshots below show this code used to create a user defined function (UDF) to solve quadratic equations (included in the download file).  Click on any image for full size view.

Code Generator


Function code

Code range selection

Posted in Excel, VBA | Tagged , , | 1 Comment

Lateral pile analyis with PY curves …

… and non-linear pile properties.

In previous posts I have presented Excel User Defined Functions (UDFs) to analyse a laterally loaded pile, generate soil PY Curves based on the recommendations in the COM624 Manual, and determine the flexural stiffness of cracked reinforced concrete sections for rectangular and circular sections.  I have now combined these into one spreadsheet to provide a convenient and rapid analysis of laterally loaded piles, taking account of both soil and concrete non-linearity.

The spreadsheet includes full open source code, and may be downloaded from LatPilePY.zip.

New features in the functions include:

  • Soil PY curves may be automatically generated or externally generated curves may be used
  • The pile may be divided into any number of sections, each with either a fixed flexural rigidity, or for circular or rectangular reinforced concrete sections, a  calculated rigidity, based on the section properties, applied bending moment and axial load, and the concrete tensile strength  and modulus.
  • The flexural stiffness of reinforced concrete sections is based on the method specified in Eurocode 2, and includes the effects of tension stiffening, loss of tension stiffening, and shrinkage and creep.

Typical input and output are shown in the screen shots below; further details are given in the spreadsheet.

LatPilePY, Input 1

LatPilePY, Input 2

LatPilePY, Input 3

LatPilePY, Output

LatPilePY, Deflection

LatPilePY, Bending Moments

LatPilePY, Shear Forces

Posted in Concrete, Excel, Geotechnical Engineering, Newton, UDFs, VBA | Tagged , , , , , | 17 Comments

Arches, anagrams and plagiarism

A previous post discussed Robert Hooke’s solution for the optimum shape of an ach structure standing under its own weight:

“Ut pendet continuum flexile, sic stabit contiguum rigidum inversum”
which translates as:
“As hangs the flexible line, so but inverted will stand the rigid arch

This statement was written by Hooke as an anagram, and only solved and translated after his death.  I noted at the end that the anagram had been miscopied at some stage,  with the insertion of an extra “e”, and the miscopied version seemed to have been accepted as correct, even at a site with an image of the original version.

Looking more closely, there are actually three errors in the “standard version”:

  • An extra e
  • An extra i
  • A v changed to a u

This analysis was done with the aid of a spreadsheet to count the letters in the solved text:

Click for full size view

Doing a Google search on the Internet version gets 121 results

Searching on Hooke’s version gets just 3 hits, two to this site, and one to a rather strange site who have copied my words exactly, other than changing “I” to “we” in a couple of places.

Posted in Arch structures, Newton | Tagged , , , | 3 Comments