Search code examples
c#incrementlogarithm

Logarithmic increment


Is there a method or command to increment logarithmic?
So how I can increment Integer:

int i = 0
while (i < 100)
{
   i++
}

result: 1, 2, 3 ... ,100

Up to now I'm doing this:

double i = 0;
while (i < 100)
{
    if (i >= 10)
    {
        i += 10;
    }
    else if (i >= 1 & i < 10)
    {
        i += 1;
    }
    else if (i >= 0.1 & i < 1)
    {
        i += 0.1;
    }
    else if (i < 0.1)
    {
        i += 0.01;
    }         
}

result: 0.1, 0.2, 0.3 ... 1, 2, 3 .... 10, 20, 30 ... 100

With a bigger range from 0.001 - 1000 is that troublesome

The second question is:
If i = 0.05 and I increment i += 0.01 then is the result 0.060000000000000005. Why it increment 0.010000000000000005 and not 0.01?


Solution

  • you could shorten your code with two for next loops, leave al the if/elses and replace them with a Math.Pow. n defines the granularity (n^-2 = 0,01)

    int n,m;
    for( n=-2 ; n < 3; n++ )
    {
        for( m= 1 ; m < 10 ; m++ )
        {
            Console.WriteLine(m * Math.Pow(10,n));
        }
    }
    

    result: 0,01 , 0,02 , 0,03 , 0,04 , 0,05 , 0,06 , 0,07 , 0,08 , 0,09 , 0,1 , 0,2 , 0,3 , 0,4 , 0,5 , 0,6 , 0,7 , 0,8 , 0,9 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 20 , 30 , 40 , 50 , 60 , 70 , 80 , 90 , 100 , 200 , 300 , 400 , 500 , 600 , 700 , 800 , 900