Created
June 4, 2018 21:24
-
-
Save eerhardt/91698ac44abdb298ce6c693bb27299cd to your computer and use it in GitHub Desktop.
Complex Division Benchmark
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using BenchmarkDotNet.Attributes; | |
using BenchmarkDotNet.Running; | |
using System; | |
using System.Numerics; | |
namespace ComplexBenchmark | |
{ | |
public class Program | |
{ | |
public static void Main(string[] args) | |
{ | |
var summary = BenchmarkRunner.Run<ComplexBenchmark>(); | |
} | |
} | |
public class ComplexBenchmark | |
{ | |
private readonly (double, Complex)[] values; | |
public ComplexBenchmark() | |
{ | |
values = new[] | |
{ | |
(15.61234, new Complex(15, 10)), | |
(0.1234, new Complex(1, 255)), | |
(0.899, new Complex(642123.6, 1)), | |
(5, new Complex(29, 33)), | |
}; | |
} | |
[Benchmark] | |
public void Original() | |
{ | |
foreach ((double, Complex) value in values) | |
{ | |
var a = DivideOriginal(value.Item1, value.Item2); | |
} | |
} | |
[Benchmark] | |
public void Simplified() | |
{ | |
foreach ((double, Complex) value in values) | |
{ | |
var a = DivideSimplified(value.Item1, value.Item2); | |
} | |
} | |
public static Complex DivideOriginal(double left, Complex right) | |
{ | |
// Division : Smith's formula. | |
double a = left; | |
double c = right.Real; | |
double d = right.Imaginary; | |
if (Math.Abs(d) < Math.Abs(c)) | |
{ | |
double doc = d / c; | |
return new Complex(a / (c + d * doc), (-a * doc) / (c + d * doc)); | |
} | |
else | |
{ | |
double cod = c / d; | |
return new Complex(a * cod / (d + c * cod), -a / (d + c * cod)); | |
} | |
} | |
public static Complex DivideSimplified(double left, Complex right) | |
{ | |
// a a c-di ac -ad | |
// ---- = ---- X ---- = ----- + ---- i | |
// c+di c+di c-di cc+dd cc+dd | |
double a = left; | |
double c = right.Real; | |
double d = right.Imaginary; | |
double divisor = (c * c) + (d * d); | |
return new Complex((a * c) / divisor, -(a * d) / divisor); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment