Unheil
Unheil

Reputation: 13

My calculation keeps adding 1 every time instead of actually calculating the right number

So I have to make a program that prints how many times it has to make a certain calculation. However, when I print the result, I seem to be getting 16000 numbers that just add +1 every new time. My question is how to fix this. I have no idea...

Thank you for your help!

My code:

class Program
{
    static void Main(string[] args)
    {
        double a = 0;
        double b = 0;
        double distance = 0;
        int i = 1;
        for (double x = -2; x < 2; x = x+0.01)
        {
            for (double y = -2; y < 2; y = y+ 0.01)
            {
                while(distance <= 2 || i < 100)
                {
                    a = a * a - b * b + x;
                    b = 2 * a * b + y;
                    double a2b2 = Math.Pow(a, 2) + Math.Pow(b, 2);
                    distance = Math.Sqrt(a2b2);
                    i++;
                }
                Console.WriteLine(i);
            }
        }
        Console.ReadKey();
    }
}

Upvotes: 0

Views: 155

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1499740

I assume you're trying to plot a fractal of some description - I haven't checked the maths, but it reminds me of code I've used to generate Mandelbrot set images before now.

The problem is that you should be creating an independent calculation for each point - but you're maintaining the state of a, b, i and distance between points. That means once distance has become greater than 2 and i is greater than 100, you'll never get into the inside of the while loop. Just move the declaration and initialization of those variables to inside your inner for loop.

Additionally, the conditions for your while loop should be ANDed together rather than ORed together, assuming that the idea is to effectively limit it to 100 iterations per point.

for (double x = -2; x < 2; x += 0.01)
{
    for (double y = -2; y < 2; y += 0.01)
    {
        // Initialize the local variables here, as they're meant to be independent for each point.
        double a = 0;
        double b = 0;
        double distance = 0;
        int i = 1;

        while (distance <= 2 && i < 100)
        {
            a = a * a - b * b + x;
            b = 2 * a * b + y;
            double a2b2 = Math.Pow(a, 2) + Math.Pow(b, 2);
            distance = Math.Sqrt(a2b2);
            i++;
        }
        Console.WriteLine(i);
    }
}

Upvotes: 3

Ondřej Kol&#225;ř
Ondřej Kol&#225;ř

Reputation: 1

The double type means floating point type. See wiki. This type is not the right numeric type for precise addition like you use. Instead of that use decimal type.

Upvotes: -1

Related Questions