"There is a better way to ask!" "There is a better sauce!" I think there are some indications such as. The purpose of this article is to "lead the correct answer by programming". I hope you can see it with warm eyes.
What is the Three Square Theorem?
In a right triangle like the image
\begin{equation}a^2+b^2=c^2\end{equation}
Is true.
If you implement this in C # by relying on the Math
class ...
//c = a^2 + b^2.
c = Math.Sqrt(Math.Pow(a, 2) + Math.Pow(b, 2));
As mentioned above, it is easy to implement.
Pow
stands for Power
, which is a function that finds the power of a certain value.
In this case, we are looking for the squares of the variables ʻa,
b. And
Sqrt stands for
Square root`, which finds a certain number of square roots.
Let's implement these necessary processes on our own.
//<summary>
//A function that finds the power of a value
//<param name="v1">Value you want to find</param>
//<param name="accuracy">Exponentiation to specify</param>
//</summary>
public static double Power(double v1, Int32 v2)
{
if (v2 < 1) return 0;
Int32 counter;
double result = 1;
Boolean isNegative = v2 < 0;
//Assuming the variable is negative
//nn = v2 < 0 ? (-1) * v2 : v2;Same as above
if (isNegative)
{
counter = (-1) * v2;
}
else
{
counter = v2;
}
for (Int32 j = 0; j < counter; j++)
{
result *= v1;
}
if (isNegative)
{
result = (1 / result);
}
return result;
}
//<summary>
//Function to find the square root
//<param name="v1">The value for which you want to find the square root</param>
//<param name="accuracy">accuracy. 9~10 is accurate. Initial value 10</param>
//</summary>
public static double SquareRoot(double v1, Int32 accuracy = 10)
{
if (accuracy < 1) return 0;
double result = v1;
for(int x = 0; x < accuracy; x++)
{
//result = (result + v1 / result) / 2.Same as 0
var n1 = v1 / result;
var n2 = result + n1;
result = n2 / 2.0;
}
return result;
}
For confirmation, I compared it with the original one.
Source code:
Program.cs
using System;
namespace MathSqrt
{
class MainClass
{
//a^2 + b^2 = c^2
static double a = 12;
static double b = 5;
static double c = 0;
public static void Main(string[] args)
{
Console.WriteLine("Hello Math!");
var na = MyMath.Power(a, 2);
var nb = MyMath.Power(b, 2);
c = MyMath.SquareRoot(na+nb);
Console.WriteLine("Three Square Theorem (Math):{0}", Math.Sqrt(Math.Pow(a, 2) + Math.Pow(b, 2)));
Console.WriteLine("Three Square Theorem (Square Math):{0}", c);
Console.ReadKey();
}
}
}
Thank you for watching until the end. If you have any typographical errors / mistakes, please let us know in the comments.
Recommended Posts