Feedforward backPropagation networks to approximate linear functions using c# - c#

I'm studying the feedforward backPropagation networks and using the "Accord.Neuro" libraries in c# (I used the ResilientBackpropagationLearning class that manages the "momentum" itself).
At this time my problem is to understand how to approximate the functions, especially those that are linear combinations of the input variables (hence the simplest ones).
Learning is supervised and one example is this: 3 variables -> y (x1, x2, x3) = 2 * x1 + x2 + 5 * x3.
I started studying functions on a single variable, then with 2, then with 3 variables and I managed to get results that I find satisfactory.
I managed to dimension the net and get good results.
---Case 3 Inputs:
3 INPUT
1 Hidden layer where there are 15 knots
1 OUTPUT
Training set, randomly generated on the input variable ranges, of 100 examples.
Training of 1000 Epochs(but also less).
I can get a network error of less than 0.001 and an average percentage error on the validation set of 1-2%.
---Try it now with 4 inputs
4 INPUT
1 Hidden layer where there are 25 knots
1 OUTPUT
Training set, randomly generated on the input variable ranges, of 500 examples
Training of 5000 Epochs
I can get a network error of less than 2.5 and an average percentage error on the validation set of 25-30%.
I've tried with so many configurations getting poor results. Even by increasing the number of examples up to 5000, epochs up to 100,000 and hidden nodes up to 50 I get an average percentage error on the validation set that improves but only up to 20-25%.
Why did I get so poor?
This is the base code of my program:
http://accord-framework.net/docs/html/T_Accord_Neuro_Learning_ResilientBackpropagationLearning.htm
This is my simple program:
using Accord.Neuro;
using Accord.Neuro.Learning;
using System;
namespace ConsoleApp4_1
{
class Program
{
struct struttura
{
public double INPUT1, INPUT2, INPUT3, INPUT4, OUTPUT1;
}
static void Main(string[] args)
{
bool needToStop = false;
Random rr = new Random((int)DateTime.Now.Millisecond);
int NE = 40, epoche = 50000, p;
double ERRORE = 0.00001d;
struttura[] EE = new struttura[NE];
double error = 1;
double[][] input = new double[NE][];
double[][] output = new double[NE][];
for (int u = 0; u < NE; u++) input[u] = new double[4];
for (int u = 0; u < NE; u++) output[u] = new double[1];
for (p = 0; p < NE; p++)
{
EE[p].INPUT1 = rr.Next(1, 200);
EE[p].INPUT2 = rr.Next(1, 100);
EE[p].INPUT3 = rr.Next(1, 50);
EE[p].INPUT4 = rr.Next(1, 150);
EE[p].OUTPUT1 = 0.1d * EE[p].INPUT2 + (2.0d / 3) * EE[p].INPUT1 + (7.0d / 10) * EE[p].INPUT3 + (2.0d / 3) * EE[p].INPUT4; // 278.3333333
}
for (p = 0; p < NE; p++)
{
for (int u = 0; u < NE; u++) input[u][0] = EE[u].INPUT1 / 200;
for (int u = 0; u < NE; u++) input[u][1] = EE[u].INPUT2 / 100;
for (int u = 0; u < NE; u++) input[u][2] = EE[u].INPUT3 / 50;
for (int u = 0; u < NE; u++) input[u][3] = EE[u].INPUT3 / 150;
for (int u = 0; u < NE; u++) output[u][0] = EE[u].OUTPUT1 / 278.3333333;
}
// create neural network
ActivationNetwork network = new ActivationNetwork(new SigmoidFunction(), 4, 8, 1);
// create teacher
var teacher = new ResilientBackpropagationLearning(network);
int i = 0;
// loop
while (!needToStop)
{
i++;
// run epoch of learning procedure
error = teacher.RunEpoch(input, output);
// check error value to see if we need to stop
if ((error < ERRORE) | (i == epoche)) needToStop = true;
Console.WriteLine(i + " " + error);
}
Console.WriteLine("Esempi per epoca: "+NE+" epoca: " + i + " error: " + error + "\n\n"); // bastano 408 epoche con NE = 40
double[] test1 = new double[] { 30.0d / 200, 80.0d / 100, 23.0d / 50, 100.0d/150};
double[] ris1 = network.Compute(test1);
double[] ris1Atteso1 = new double[] { 110.7666667d };
Console.WriteLine("a: " + (ris1[0] * 278.3333333d).ToString("") + " " + ris1Atteso1[0]);
double[] test2 = new double[] { 150.0d / 200, 40.0d / 100, 3.0d / 50, 40.0d/150};
double[] ris2 = network.Compute(test2);
double[] ris1Atteso2 = new double[] { 132.7666667d };
Console.WriteLine("\na: " + (ris2[0] * 278.3333333d).ToString("") + " " + ris1Atteso2[0]);
double[] test3 = new double[] { 15.0d / 200, 30.0d / 100, 45.0d / 50, 146.0d/150};
double[] ris3 = network.Compute(test3);
double[] ris1Atteso3 = new double[] { 141,8333333d };
Console.WriteLine("\na: " + (ris3[0] * 278.3333333d).ToString("") + " " + ris1Atteso3[0]);
double[] test4 = new double[] { 3.0d / 200, 60.0d / 100, 12.0d / 50, 70.0d/150};
double[] ris4 = network.Compute(test4);
double[] ris1Atteso4 = new double[] {63.0666667d};
Console.WriteLine("\na: " + (ris4[0] * 278.3333333d).ToString("") + " " + ris1Atteso4[0]);
double[] test5 = new double[] { 50.0d / 200, 2.0d / 100, 44.0d / 50, 15.0d/150};
double[] ris5 = network.Compute(test5);
double[] ris1Atteso5 = new double[] { 74,333333d };
Console.WriteLine("\na: " + (ris5[0] * 278.3333333d).ToString("") + " " + ris1Atteso5[0]);
double[] test6 = new double[] { 180.0d / 200, 95.0d / 100, 25.0d / 50, 70.0d/150 };
double[] ris6 = network.Compute(test6);
double[] ris1Atteso6 = new double[] { 193.6666667 };
Console.WriteLine("\na: " + (ris6[0] * 278.3333333d).ToString("") + " " + ris1Atteso6[0]);
double[] test7 = new double[] { 22.0d / 200, 12.0d / 100, 2.0d / 50, 10.0d/150 };
double[] ris7 = network.Compute(test7);
double[] ris1Atteso7 = new double[] { 23.9333333d };
Console.WriteLine("\na: " + (ris7[0] * 278.3333333d).ToString("") + " " + ris1Atteso7[0]);
double[] test8 = new double[] { 35.0d / 200, 5.0d / 100, 40.0d / 50, 120.0d/150 };
double[] ris8 = network.Compute(test8);
double[] ris1Atteso8 = new double[] { 131.8333333d };
Console.WriteLine("\na: " + (ris8[0] * 278.3333333d).ToString("") + " " + ris1Atteso8[0]);
double[] test9 = new double[] { 115.0d / 200, 70.0d / 100, 50.0d / 50, 88.0d/150};
double[] ris9 = network.Compute(test9);
double[] ris1Atteso9 = new double[] { 177.3333333d };
Console.WriteLine("\na: " + (ris9[0] * 278.3333333d).ToString("") + " " + ris1Atteso9[0]);
double[] test10 = new double[] { 18.0d / 200, 88.0d / 100, 1.0d / 50, 72.0d/150 };
double[] ris10 = network.Compute(test10);
double[] ris1Atteso10 = new double[] { 69.5d };
Console.WriteLine("\na: " + (ris10[0] * 278.3333333d).ToString("") + " " + ris1Atteso10[0]);
double sum = Math.Abs(ris1[0] * 278.3333333d - ris1Atteso1[0])+ Math.Abs(ris2[0] * 278.3333333d - ris1Atteso2[0]) + Math.Abs(ris3[0] * 278.3333333d - ris1Atteso3[0]) + Math.Abs(ris4[0] * 278.3333333d - ris1Atteso4[0]) + Math.Abs(ris5[0] * 278.3333333d - ris1Atteso5[0])
+ Math.Abs(ris6[0] * 278.3333333d - ris1Atteso6[0]) + Math.Abs(ris7[0] * 278.3333333d - ris1Atteso7[0]) + Math.Abs(ris8[0] * 278.3333333d - ris1Atteso8[0]) + Math.Abs(ris9[0] * 278.3333333d - ris1Atteso9[0]) + Math.Abs(ris10[0] * 278.3333333d - ris1Atteso10[0]);
double erroreMedio = sum / 10;
double sumMedie = Math.Abs((ris1[0] * 278.3333d - ris1Atteso1[0]) / (ris1Atteso1[0]))
+ Math.Abs((ris2[0] * 278.3333d - ris1Atteso2[0]) / (ris1Atteso2[0]))
+ Math.Abs((ris3[0] * 278.3333d - ris1Atteso3[0]) / (ris1Atteso3[0]))
+ Math.Abs((ris4[0] * 278.3333d - ris1Atteso4[0]) / (ris1Atteso4[0]))
+ Math.Abs((ris5[0] * 278.3333d - ris1Atteso5[0]) / (ris1Atteso5[0]))
+ Math.Abs((ris6[0] * 278.3333d - ris1Atteso6[0]) / (ris1Atteso6[0]))
+ Math.Abs((ris7[0] * 278.3333d - ris1Atteso7[0]) / (ris1Atteso7[0]))
+ Math.Abs((ris8[0] * 278.3333d - ris1Atteso8[0]) / (ris1Atteso8[0]))
+ Math.Abs((ris9[0] * 278.3333d - ris1Atteso9[0]) / (ris1Atteso9[0]))
+ Math.Abs((ris10[0] * 278.3333d - ris1Atteso10[0]) / (ris1Atteso10[0]));
Console.WriteLine("\nErrore medio su 10 : "+ erroreMedio);
Console.WriteLine("\nErrore % medio : " + (sumMedie/10)*100);
Console.ReadLine();
}
}
}

Although i'm unfamiliar with Accord.
You seam to hit a classical problem that can happen to wrong dimensioned networks.
The neural network gets (extreme) good on training sets but not on practical sets.
I think you should try it with less hidden neurons.
As your network learned to much the training set resulting in that it cannt handle different data. As it would be better to score 85%-train and 79%-validation. As compared to 99%-train and 65%-validation. Notice that those % numbers the total % of both network is the same (85+79)=(99+65), but the first network would be better in solving unknown thing; and thats the general goal.
The term for what you have now is called over fitting.
Most often caused by that the network starts to act more like memory, it memorizes treshold, while it should be more about decision making in the unknown validation sets. Well i hope this helps.
Also be aware that with less hidden neurons, its also possible to not achieve near 100% on train set, but eventually its not about solving that one, keep that in mind.
Also not sure what you try to solve with it, but make sure your data set has the right neural network, for simple testing fun try to Irish-flower data set. My networks can score 199.16% or so on that in combined (trained+validation). You might try to beat that and if so give me an update :)

Related

Having trouble in finding roots of a cubic equation with C#

Recently my friends and I decided to make a multi-functional calculator to automatically find
the roots of quadratic equations.
It wasn't that challenging after all, so we decided to go onto the next level, to make a calculator for a cubic equation.
(ax^3 + bx^2 + cx + d)
However, we stumbled across some trivial problems, and no matter how hard we tried, the results are still the same.
we are beginners in terms of coding, so we're not sure if we are actually making some stupid mistakes here
but at least we want to learn something from others.
Basically, we have tried a lot of combinations of different cubic equations, or even re-coding the whole thing. The problem is that the results we yield are always wrong, but only for the real parts of the second root and third root.
For a better understanding, we have tried 9x^3 + 8x^2 + 7x + 6, as an example.
The correct answer, according to a cubic equation calculator website, is
(The website)
First root = -0.87285
Second root = -0.00802 + 0.87391 i
Third root = -0.00802 - 0.87391 i
However, our result to this equation is :
First root = -0.87285
Second root = -0.2963 + 0.87391 i
Third root = -0.2963 + -0.87391 i
It is apparently noticeable that only parts of the second and third roots are wrong.
We have tried finding similar threads to help, but those are a little bit too difficult for us to understand or those problems are not the same as ours.
We look forward to finding the solution and the causes to this problem.
We have separated the formulas for finding the roots of a cubic equation into 5 parts.
(rootp1-rootp5)
The formulas are coded according to the formulas that can be found in the Chinese version of Wikipedia's page of Cubic equation.
(The formulas)
We have also rounded the real parts of the roots to 5 digits.
(Some code lines might be redundant, but as I have mentioned, we are new to coding)
Code (C#) :
using System;
using System.Numerics;
namespace ComplexNumbers
{
public class ComplexNo
{
public static void Main()
{
Console.WriteLine("Cubic Equation Calculator :");
Console.Write("Insert first coefficient : ");
double a = Convert.ToDouble(Console.ReadLine());
Console.Write("Insert second coefficient : ");
double b = Convert.ToDouble(Console.ReadLine());
Console.Write("Insert third coefficient : ");
double c = Convert.ToDouble(Console.ReadLine());
Console.Write("Insert constant : ");
double d = Convert.ToDouble(Console.ReadLine());
Console.WriteLine(" ");
Console.WriteLine("Solve for " + a + "x" + "^3 " + b + "x^2 " + c + "x " + d + " :");
double rootp1 = -(b / (3 * a));
double rootp2 = (b * c / (6 * Math.Pow(a, 2))) - (Math.Pow(b, 3) / (27 * Math.Pow(a, 3))) - (d / (2 * a));
double rootp3 = (c / (3 * a)) - (Math.Pow(b, 2) / (9 * Math.Pow(a, 2)));
Complex root1 = rootp1 + Math.Cbrt(rootp2 + Math.Sqrt(Math.Pow(rootp2, 2) + Math.Pow(rootp3, 3))) +
Math.Cbrt(rootp2 - Math.Sqrt(Math.Pow(rootp2, 2) + Math.Pow(rootp3, 3)));
Complex rootp4 = new Complex(-1 / 2, Math.Sqrt(3) / 2);
Complex rootp5 = new Complex(-1 / 2, -(Math.Sqrt(3) / 2));
Complex root2 = rootp1 + (rootp4 * Math.Cbrt(rootp2 + Math.Sqrt(Math.Pow(rootp2, 2) + Math.Pow(rootp3, 3)))) +
(rootp5 * Math.Cbrt(rootp2 - Math.Sqrt(Math.Pow(rootp2, 2) + Math.Pow(rootp3, 3))));
Complex root3 = rootp1 + (rootp5 * Math.Cbrt(rootp2 + Math.Sqrt(Math.Pow(rootp2, 2) + Math.Pow(rootp3, 3)))) +
(rootp4 * Math.Cbrt(rootp2 - Math.Sqrt(Math.Pow(rootp2, 2) + Math.Pow(rootp3, 3))));
Console.WriteLine(" ");
Console.WriteLine("Results :");
Console.WriteLine("First Root :");
string root1rp = Convert.ToString(Math.Round(root1.Real, 5));
string root1ip = Convert.ToString(Math.Round(root1.Imaginary, 5));
Console.WriteLine(root1rp + " + " + root1ip + "i");
Console.WriteLine("Second Root :");
string root2rp = Convert.ToString(Math.Round(root2.Real, 5));
string root2ip = Convert.ToString(Math.Round(root2.Imaginary, 5));
Console.WriteLine(root2rp + " + " + root2ip + "i");
Console.WriteLine("Third Root :");
string root3rp = Convert.ToString(Math.Round(root3.Real, 5));
string root3ip = Convert.ToString(Math.Round(root3.Imaginary, 5));
Console.WriteLine(root3rp + " + " + root3ip + "i");
Console.ReadLine();
}
}
}
(Sorry for making this thread so long and my bad grammar)
The problem is with this line Complex rootp4 = new Complex(-1 / 2, Math.Sqrt(3) / 2);. -1/2 uses integer division and evaluates to 0.
This code will work.
Console.WriteLine(" ");
Console.WriteLine("Solve for " + a + "x" + "^3 " + b + "x^2 " + c + "x " + d + " :");
double minusBover3a = -(b / (3 * a));
double rootp2 = (b * c / (6 * Math.Pow(a, 2))) - (Math.Pow(b, 3) / (27 * Math.Pow(a, 3))) - (d / (2 * a));
double rootp3 = (c / (3 * a)) - (Math.Pow(b, 2) / (9 * Math.Pow(a, 2)));
double bigCubeRootPlus = Math.Cbrt(rootp2 + Math.Sqrt(Math.Pow(rootp2, 2) + Math.Pow(rootp3, 3)));
double bigCubeRootMinus = Math.Cbrt(rootp2 - Math.Sqrt(Math.Pow(rootp2, 2) + Math.Pow(rootp3, 3)));
// ** THIS IS THE PROBLEM. "-1/2" uses integer division, so this complex has 0 for real part
Complex complexPlus = new Complex(-1.0 / 2, Math.Sqrt(3) / 2);
Complex complexMinus = new Complex(-1.0 / 2, -(Math.Sqrt(3) / 2));
Complex root1 = minusBover3a + bigCubeRootPlus + bigCubeRootMinus;
Complex root2 = minusBover3a + complexPlus * bigCubeRootPlus + complexMinus * bigCubeRootMinus;
Complex root3 = minusBover3a + complexMinus * bigCubeRootPlus + complexPlus * bigCubeRootMinus;
I admit I haven't tried your code, but you may have a casting issue in the math in your original calculations. Try this:
double rootp2 = ((double)b * (double)c / (6D * Math.Pow(a, 2D))) - (Math.Pow(b, 3D) / (27D * Math.Pow(a, 3D))) - ((double)d / (2D * (double)a));
If that makes a difference, you'd have to propagate a similar change (cast all variables as (double) and inline constants as double with D) through the other calculations.
The following is an alternative to your code:
// from https://www.daniweb.com/programming/software-development/
// code/454493/solving-the-cubic-equation-using-the-complex-struct
// algorithm described in
// https://en.wikipedia.org/wiki/Cubic_equation#General_cubic_formula
const int NRoots = 3;
double SquareRootof3 = Math.Sqrt(3);
// the 3 cubic roots of 1
var CubicUnity = new List<Complex>(NRoots)
{ new Complex(1, 0),
new Complex(-0.5, -SquareRootof3 / 2.0),
new Complex(-0.5, SquareRootof3 / 2.0) };
// intermediate calculations
double DELTA = 18 * a * b * c * d
- 4 * b * b * b * d
+ b * b * c * c
- 4 * a * c * c * c
- 27 * a * a * d * d;
double DELTA0 = b * b - 3 * a * c;
double DELTA1 = 2 * b * b * b
- 9 * a * b * c
+ 27 * a * a * d;
Complex DELTA2 = -27 * a * a * DELTA;
Complex C = Complex.Pow((DELTA1 + Complex.Pow(DELTA2, 0.5)) / 2, 1 / 3.0);
for (int i = 0; i < NRoots; i++)
{
Complex M = CubicUnity[i] * C;
Complex Root = -1.0 / (3 * a) * (b + M + DELTA0 / M);
Console.WriteLine();
Console.WriteLine($"Root {i+1}:");
Console.WriteLine($"Real {Root.Real:0.#####}");
Console.WriteLine($"Imaginary {Root.Imaginary:0.#####}i");
}

Amortisation schedule, monthly principal decreasing instead of increasing

Hi I am trying to create a amortization schedule , which shows the EMI , Principal , Interest and the new Principal for next month. The problem is that the monthly principal instead of increasing keeps on decreasing. As far as from searching the net , I am doing the right calculations. What am I missing?
decimal principal = 312500;
decimal rate = 3.50M;
decimal EMI;
decimal monthlyInterest;
decimal monthlyPrincipal;
decimal newPrincipalBalance;
decimal downPayment = 62500;
decimal actualPrincipal = principal - downPayment;
for (int i = 0; i <= 24; i++)
{
Console.WriteLine("principal " + actualPrincipal);
EMI = Math.Round(monthlyPayments(actualPrincipal, rate, 30));
Console.WriteLine("EMI " + EMI);
monthlyInterest = actualPrincipal * rate / 12;
monthlyInterest = Math.Round((actualPrincipal * rate / 100) / 12);
Console.WriteLine("monthlyInterest " + monthlyInterest);
monthlyPrincipal = Math.Round(EMI - monthlyInterest);
Console.WriteLine("monthlyPrincipal " + monthlyPrincipal);
newPrincipalBalance = Math.Round(actualPrincipal - monthlyPrincipal);
Console.WriteLine("newPrincipalBalance " + newPrincipalBalance);
Console.WriteLine("===================================");
actualPrincipal = newPrincipalBalance;
}
}
public static decimal monthlyPayments(decimal actualPrincipal, decimal rate, int years)
{
rate = rate / 1200;
years = years * 12;
decimal F = (decimal)Math.Pow((double)(1 + rate), years);
return actualPrincipal * (rate * F) / (F - 1);
}
These are first few of my results where the monthly principal is decreasing
This is what the expected result is :
This is the formula for calculating the monthlyPayments
I found what I was doing wrong. As the EMI remains fixed for the entire period of the loan, it should have been kept outside the loop.
Console.WriteLine("principal " + actualPrincipal);
EMI = Math.Round(monthlyPayments(actualPrincipal, rate, 30));
Console.WriteLine("EMI " + EMI);
for (int i = 0; i <= 24; i++)
{
monthlyInterest = actualPrincipal * rate / 12;
monthlyInterest = Math.Round((actualPrincipal * rate / 100) / 12);
Console.WriteLine("monthlyInterest " + monthlyInterest);
monthlyPrincipal = Math.Round(EMI - monthlyInterest);
Console.WriteLine("monthlyPrincipal " + monthlyPrincipal);
newPrincipalBalance = Math.Round(actualPrincipal - monthlyPrincipal);
Console.WriteLine("newPrincipalBalance " + newPrincipalBalance);
Console.WriteLine("===================================");
actualPrincipal = newPrincipalBalance;
}

Solving equation to find center point of circle from 3 points

I'm looking for a high precision solution to find the center point of a circle from 3 data points on a canvas (x,y). I found this example in the attached screenshot above, now I'm using the Math.NET package to solve the equation and I'm comparing the results against this online tool: https://planetcalc.com/8116/.
However, when I calculate the radius its completely off and often a negative number???
using MathNet.Numerics.LinearAlgebra.Double.Solvers;
using MathNet.Numerics.LinearAlgebra.Double;
using System;
namespace ConsoleAppTestBed
{
class Program
{
static void Main(string[] args)
{
var dataPoints = new double[,]
{
{ 5, 80 },
{ 20, 100 },
{ 40, 140 }
};
var fitter = new CircleFitter();
var result = fitter.Fit(dataPoints);
var x = -result[0];
var y = -result[1];
var c = result[2];
Console.WriteLine("Center Point:");
Console.WriteLine(x);
Console.WriteLine(y);
Console.WriteLine(c);
//// (x^2 + y^2 - c^2)
var radius = Math.Pow(x, 2) + Math.Pow(y, 2) - Math.Pow(c, 2);
//// sqrt((x^2 + y^2 - c^2))
radius = Math.Sqrt(radius);
Console.WriteLine("Radius:");
Console.WriteLine(radius);
Console.ReadLine();
}
public class CircleFitter
{
public double[] Fit(double[,] v)
{
var xy1 = new double[] { v[0,0], v[0,1] };
var xy2= new double[] { v[1, 0], v[1, 1] };
var xy3 = new double[] { v[2, 0], v[2, 1] };
// Create Left Side Matrix of Equation
var a = CreateLeftSide_(xy1);
var b = CreateLeftSide_(xy2);
var c = CreateLeftSide_(xy3);
var matrixA = DenseMatrix.OfArray(new[,]
{
{ a[0], a[1], a[2] },
{ b[0], b[1], b[2] },
{ c[0], c[1], c[2] }
});
// Create Right Side Vector of Equation
var d = CreateRightSide_(xy1);
var e = CreateRightSide_(xy2);
var f = CreateRightSide_(xy3);
double[] vector = { d, e, f };
var vectorB = Vector<double>.Build.Dense(vector);
// Solve Equation
var r = matrixA.Solve(vectorB);
var result = r.ToArray();
return result;
}
//2x, 2y, 1
public double[] CreateLeftSide_(double[] d)
{
return new double[] { (2 * d[0]), (2 * d[1]) , 1};
}
// -(x^2 + y^2)
public double CreateRightSide_(double[] d)
{
return -(Math.Pow(d[0], 2) + Math.Pow(d[1], 2));
}
}
}
}
Any ideas?
Thanks in advance.
The solution to your problem is here: The NumberDecimalDigits property
Code:
using System;
using System.Globalization;
namespace ConsoleApp1
{
class Program
{
static void Main()
{
double x1 = 1, y1 = 1;
double x2 = 2, y2 = 4;
double x3 = 5, y3 = -3;
findCircle(x1, y1, x2, y2, x3, y3);
Console.ReadKey();
}
static void findCircle(double x1, double y1,
double x2, double y2,
double x3, double y3)
{
NumberFormatInfo setPrecision = new NumberFormatInfo();
setPrecision.NumberDecimalDigits = 3; // 3 digits after the double point
double x12 = x1 - x2;
double x13 = x1 - x3;
double y12 = y1 - y2;
double y13 = y1 - y3;
double y31 = y3 - y1;
double y21 = y2 - y1;
double x31 = x3 - x1;
double x21 = x2 - x1;
double sx13 = (double)(Math.Pow(x1, 2) -
Math.Pow(x3, 2));
double sy13 = (double)(Math.Pow(y1, 2) -
Math.Pow(y3, 2));
double sx21 = (double)(Math.Pow(x2, 2) -
Math.Pow(x1, 2));
double sy21 = (double)(Math.Pow(y2, 2) -
Math.Pow(y1, 2));
double f = ((sx13) * (x12)
+ (sy13) * (x12)
+ (sx21) * (x13)
+ (sy21) * (x13))
/ (2 * ((y31) * (x12) - (y21) * (x13)));
double g = ((sx13) * (y12)
+ (sy13) * (y12)
+ (sx21) * (y13)
+ (sy21) * (y13))
/ (2 * ((x31) * (y12) - (x21) * (y13)));
double c = -(double)Math.Pow(x1, 2) - (double)Math.Pow(y1, 2) -
2 * g * x1 - 2 * f * y1;
double h = -g;
double k = -f;
double sqr_of_r = h * h + k * k - c;
// r is the radius
double r = Math.Round(Math.Sqrt(sqr_of_r), 5);
Console.WriteLine("Center of a circle: x = " + h.ToString("N", setPrecision) +
", y = " + k.ToString("N", setPrecision));
Console.WriteLine("Radius: " + r.ToString("N", setPrecision));
}
}
}
I have just converted William Li's answer to Swift 5 for
those who like to cmd+C and cmd+V like me :)
func calculateCircle(){
let x1:Float = 0
let y1:Float = 0
let x2:Float = 0.5
let y2:Float = 0.5
let x3:Float = 1
let y3:Float = 0
let x12 = x1 - x2
let x13 = x1 - x3
let y12 = y1 - y2
let y13 = y1 - y3
let y31 = y3 - y1
let y21 = y2 - y1
let x31 = x3 - x1
let x21 = x2 - x1
let sx13 = pow(x1, 2) - pow(x3, 2)
let sy13 = pow(y1, 2) - pow(y3, 2)
let sx21 = pow(x2, 2) - pow(x1, 2)
let sy21 = pow(y2, 2) - pow(y1, 2)
let f = ((sx13) * (x12)
+ (sy13) * (x12)
+ (sx21) * (x13)
+ (sy21) * (x13))
/ (2 * ((y31) * (x12) - (y21) * (x13)))
let g = ((sx13) * (y12)
+ (sy13) * (y12)
+ (sx21) * (y13)
+ (sy21) * (y13))
/ (2 * ((x31) * (y12) - (x21) * (y13)))
let c = -pow(x1, 2) - pow(y1, 2) - 2 * g * x1 - 2 * f * y1
let h = -g
let k = -f
let r = sqrt(h * h + k * k - c)
print("center x = \(h)")
print("center y = \(k)")
print("r = \(r)")
}
Updated Answer
The equation for radius is incorrect; it should be (not c squared):
which is why you get incorrect values for the radius.
The original answer was incorrect, but it is still 'interesting'.
(Incorrect) Original Answer
The cause of the problematic calculation is not solely due to the precision of the numbers, but more because problem is ill-conditioned. If you look at the three points and where they are located on the circle, you'll see that they are bunched on a small segment of the circumference. When the points are so close to each other, it is a tough ask to find the circle's centre and radius accurately.
So the intermediate calculations, which will have small rounding errors, result in hugely exaggerated errors.
You can see the ill-conditioned nature of the problem by adding the ConditionNumber() method.
// Solve Equation
Console.WriteLine(matrixA.ConditionNumber()); // <<< Returns 5800 -> Big!
var r = matrixA.Solve(vectorB); // Existing code
A large result indicates an ill-conditioned problem. In this case a value of 5800 is returned, which is large. You might get better results using Gaussian Elimination with partial pivoting, but it still does not address the fact that the basic problem is ill-conditioned, which is why you get wildly incorrect answers.

How would i work out magnitude quickly for 3 values?

How can I use a Fast Magnitude calculation for 3 values (instead of using square root)? (+/- 3% is good enough)
public void RGBToComparison(Color32[] color)
{
DateTime start = DateTime.Now;
foreach (Color32 i in color)
{
var r = PivotRgb(i.r / 255.0);
var g = PivotRgb(i.g / 255.0);
var b = PivotRgb(i.b / 255.0);
var X = r * 0.4124 + g * 0.3576 + b * 0.1805;
var Y = r * 0.2126 + g * 0.7152 + b * 0.0722;
var Z = r * 0.0193 + g * 0.1192 + b * 0.9505;
var LB = PivotXyz(X / 95.047);
var AB = PivotXyz(Y / 100);
var BB = PivotXyz(Z / 108.883);
var L = Math.Max(0, 116 * AB - 16);
var A = 500 * (LB - AB);
var B = 200 * (AB - BB);
totalDifference += Math.Sqrt((L-LT)*(L-LT) + (A-AT)*(A-AT) + (B-BT)*(B-BT));
}
totalDifference = totalDifference / color.Length;
text.text = "Amount of Pixels: " + color.Length + " Time(MilliSeconds):" + DateTime.Now.Subtract(start).TotalMilliseconds + " Score (0 to 100)" + (totalDifference).ToString();
RandomOrNot();
}
private static double PivotRgb(double n)
{
return (n > 0.04045 ? Math.Pow((n + 0.055) / 1.055, 2.4) : n / 12.92) * 100.0;
}
private static double PivotXyz(double n)
{
return n > 0.008856 ? CubicRoot(n) : (903.3 * n + 16) / 116;
}
private static double CubicRoot(double n)
{
return Math.Pow(n, 1.0 / 3.0);
}
This is the important part: totalDifference += Math.Sqrt((L-LT)*(L-LT) + (A-AT)*(A-AT) + (B-BT)*(B-BT));
I know there are FastMagnitude calculations online, but all the ones online are for two values, not three. For example, could i use the difference between the values to get a precise answer? (By implementing the difference value into the equation, and if the difference percentage-wise is big, falling back onto square root?)
Adding up the values and iterating the square root every 4 pixels is a last resort that I could do. But firstly, I want to find out if it is possible to have a good FastMagnitude calculation for 3 values.
I know I can multi-thread and parllelize it, but I want to optimize my code before I do that.
If you just want to compare the values, why not leave the square root out and work with the length squared?
Or use the taylor series of the square root of 1+x and cut off early :)

Restart program from a certain line with an if statement?

could anyone help me restart my program from line 46 if the user enters 1 (just after the comment where it states that the next code is going to ask the user for 2 inputs) and if the user enters -1 end it. I cannot think how to do it. I'm new to C# any help you could give would be great!
class Program
{
static void Main(string[] args)
{
//Displays data in correct Format
List<float> inputList = new List<float>();
TextReader tr = new StreamReader("c:/users/tom/documents/visual studio 2010/Projects/DistanceCalculator3/DistanceCalculator3/TextFile1.txt");
String input = Convert.ToString(tr.ReadToEnd());
String[] items = input.Split(',');
Console.WriteLine("Point Latitude Longtitude Elevation");
for (int i = 0; i < items.Length; i++)
{
if (i % 3 == 0)
{
Console.Write((i / 3) + "\t\t");
}
Console.Write(items[i]);
Console.Write("\t\t");
if (((i - 2) % 3) == 0)
{
Console.WriteLine();
}
}
Console.WriteLine();
Console.WriteLine();
// Ask for two inputs from the user which is then converted into 6 floats and transfered in class Coordinates
Console.WriteLine("Please enter the two points that you wish to know the distance between:");
string point = Console.ReadLine();
string[] pointInput = point.Split(' ');
int pointNumber = Convert.ToInt16(pointInput[0]);
int pointNumber2 = Convert.ToInt16(pointInput[1]);
Coordinates distance = new Coordinates();
distance.latitude = (Convert.ToDouble(items[pointNumber * 3]));
distance.longtitude = (Convert.ToDouble(items[(pointNumber * 3) + 1]));
distance.elevation = (Convert.ToDouble(items[(pointNumber * 3) + 2]));
distance.latitude2 = (Convert.ToDouble(items[pointNumber2 * 3]));
distance.longtitude2 = (Convert.ToDouble(items[(pointNumber2 * 3) + 1]));
distance.elevation2 = (Convert.ToDouble(items[(pointNumber2 * 3) + 2]));
//Calculate the distance between two points
const double PIx = 3.141592653589793;
const double RADIO = 6371;
double dlat = ((distance.latitude2) * (PIx / 180)) - ((distance.latitude) * (PIx / 180));
double dlon = ((distance.longtitude2) * (PIx / 180)) - ((distance.longtitude) * (PIx / 180));
double a = (Math.Sin(dlat / 2) * Math.Sin(dlat / 2)) + Math.Cos((distance.latitude) * (PIx / 180)) * Math.Cos((distance.latitude2) * (PIx / 180)) * (Math.Sin(dlon / 2) * Math.Sin(dlon / 2));
double angle = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));
double ultimateDistance = (angle * RADIO);
Console.WriteLine("The distance between your two points is...");
Console.WriteLine(ultimateDistance);
//Repeat the program if the user enters 1, end the program if the user enters -1
Console.WriteLine("If you wish to calculate another distance type 1 and return, if you wish to end the program, type -1.");
Console.ReadLine();
if (Convert.ToInt16(Console.ReadLine()) == 1);
{
//here is where I need it to repeat
}
bool exit = false;
do
{
Console.WriteLine("Please enter the two points that you wish to know the distance between:");
...
Console.WriteLine("If you wish to calculate another distance type 1 and return, if you wish to end the program, type -1.");
string input;
do
{
input = Console.ReadLine().Trim();
}
while (input != "1" && input != "-1");
if (input == -1) exit = true;
}
while (!exit);
But you would do much better to think about pushing logic into methods and functions such that you program is built up of much smaller building blocks.
You should be aiming towards something like this:
bool exit = false;
do
{
Point[] points = ReadCoordinates();
Whatever result = CalculateWhatever();
DisplayResults(results);
exit = ShouldExit();
}
while (!exit);
This makes the outer loop of your program self documenting and the methods self explanatory.
if (Convert.ToInt16(Console.ReadLine()) == 1);
{
Main(args)
}
That's quite an odd thing to do.
Have you looked into the while loop?
You could make a method of the above structure and loop it, while userinput equals 1
if it equals -1, call the following statement
Application.Exit()
Can use Goto to make the program loop on user input.
public static void Main(string[] args)
{
RestartApplication:
//// Displays data in correct Format
TextReader textReader = new StreamReader("c:/users/tom/documents/visual studio 2010/Projects/DistanceCalculator3/DistanceCalculator3/TextFile1.txt");
var input = Convert.ToString(textReader.ReadToEnd());
var items = input.Split(',');
Console.WriteLine("Point Latitude Longtitude Elevation");
for (var i = 0; i < items.Length; i++)
{
if (i % 3 == 0)
{
Console.Write((i / 3) + "\t\t");
}
Console.Write(items[i]);
Console.Write("\t\t");
if (((i - 2) % 3) == 0)
{
Console.WriteLine();
}
}
Console.WriteLine();
Console.WriteLine();
//// Ask for two inputs from the user which is then converted into 6 floats and transferred in class Coordinates
Console.WriteLine("Please enter the two points that you wish to know the distance between:");
var point = Console.ReadLine();
string[] pointInput;
if (point != null)
{
pointInput = point.Split(' ');
}
else
{
goto RestartApplication;
}
var pointNumber = Convert.ToInt16(pointInput[0]);
var pointNumber2 = Convert.ToInt16(pointInput[1]);
var distance = new Coordinates
{
Latitude = Convert.ToDouble(items[pointNumber * 3]),
Longtitude = Convert.ToDouble(items[(pointNumber * 3) + 1]),
Elevation = Convert.ToDouble(items[(pointNumber * 3) + 2]),
Latitude2 = Convert.ToDouble(items[pointNumber2 * 3]),
Longtitude2 = Convert.ToDouble(items[(pointNumber2 * 3) + 1]),
Elevation2 = Convert.ToDouble(items[(pointNumber2 * 3) + 2])
};
//// Calculate the distance between two points
const double PIx = 3.141592653589793;
const double Radio = 6371;
var dlat = (distance.Latitude2 * (PIx / 180)) - (distance.Latitude * (PIx / 180));
var dlon = (distance.Longtitude2 * (PIx / 180)) - (distance.Longtitude * (PIx / 180));
var a = (Math.Sin(dlat / 2) * Math.Sin(dlat / 2)) + Math.Cos(distance.Latitude * (PIx / 180)) * Math.Cos(distance.Latitude2 * (PIx / 180)) * (Math.Sin(dlon / 2) * Math.Sin(dlon / 2));
var angle = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));
var ultimateDistance = angle * Radio;
Console.WriteLine("The distance between your two points is...");
Console.WriteLine(ultimateDistance);
//// Repeat the program if the user enters 1, end the program if the user enters -1
Console.WriteLine("If you wish to calculate another distance type 1 and return, if you wish to end the program, type -1.");
var userInput = Console.ReadLine();
if (Convert.ToInt16(userInput) == 1)
{
//// Here is where the application will repeat.
goto RestartApplication;
}
}
also did a bit of code formatting. Hope it helps.
You could do that with goto, be aware however that this is considered bad practice.
static void Main(string[] args)
{
...
MyLabel:
...
if (Convert.ToInt16(Console.ReadLine()) == 1);
{
//here is where I need it to repeat
goto MyLabel;
}

Categories