Skip to content

Instantly share code, notes, and snippets.

@jackdoerner
Created August 13, 2015 20:53
Show Gist options
  • Save jackdoerner/6bbaf464d8bdee2fbff3 to your computer and use it in GitHub Desktop.
Save jackdoerner/6bbaf464d8bdee2fbff3 to your computer and use it in GitHub Desktop.
/*
durandkerner.swift
An implementation of the Durand-Kerner/Weierstrass method for finding the roots of a polynomial
Requires Complex.swift by Dan Kogai
Copyright (c) 2015 Jack Doerner
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import Foundation
func durandKerner(function: (Complex<Double>)->(Complex<Double>), degree:Int, precision:Double) -> [Complex<Double>] {
var lastPrecision = precision + 1
var results:[Complex<Double>] = []
for (var ii = 0; ii < degree; ii++) {
results.append(pow(Complex(0.4, 0.9),rhs: Double(ii)))
}
while lastPrecision > precision {
var nextResults:[Complex<Double>] = []
var precisionOfRound = lastPrecision
for (var ii = 0; ii < degree; ii++) {
var denom = Complex<Double>(1,1)
for (var jj = 0; jj < degree; jj++) {
if jj > ii {
denom *= results[ii] - results[jj]
} else if jj < ii {
denom *= results[ii] - nextResults[jj]
}
}
let nextResult = results[ii] - function(results[ii]) / denom
nextResults.append(nextResult)
let thisPrecision:Double = (results[ii] - nextResults[ii]).abs
if (ii == 0 || thisPrecision < precisionOfRound) {
precisionOfRound = thisPrecision
}
}
if (precisionOfRound < lastPrecision) {
lastPrecision = precisionOfRound
}
results = nextResults
}
return results
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment