I wrote a simple program to solve the math problem:
A^2+B^2 = 12
A*B = 9
(A+B)^2 = y
My program is looping through each number starting at 0.000000001, and checking to see if the first equation is true (the second one is always true because I always assign double B = 9 / A).
Then it writes the results and pauses. This is taking forever to run since its doing a lot of math, I was wondering if I made any mistakes so I can fix them? Here is my code:
namespace AnnoyingMath1
{
class Program
{
static void Main(string[] args)
{
for (double a = 0.00000001; a < 9; a += 0.00000001) {
double b = 9 / a;
if (Math.Pow(a, 2) + Math.Pow(b, 2) == 12)
{
if (a * b == 9) // always true because b = 9 / a
{
Console.WriteLine("SUCCESS! a = " + a.ToString() + ", b = " + b.ToString() + ", y = (a+b)^2 = " + (Math.Pow(a + b, 2)).ToString() );
Console.ReadLine();
}
}
else {
Console.WriteLine("fail1 " + a.ToString() + " , " + b.ToString());
}
}
}
}
}
Yes. It does.
statements such as:
are incorrect.
Never directly compare floating point values. Use a delta instead:
There are many similar questions on StackOverflow.
Please read What Every Computer Scientist Should Know About Floating-Point Arithmetic