Search code examples
c#logarithm

How to get log scale between two number with a set number of steps c#


I'd like to be able to get a log scale between two numbers, for x number of steps between a max and min value in c#

E.g.

var steps = 10;
var minValue = 10;
var maxValue = 1000;

Which would return this array with the values to the nearest int

[{1,10}, {2, 17}, {3,28}, {4,46}, {5,77}, {6,129}, {7,215}, {8,359}, {9, 599}, {10, 1000}]

Can anyone point me in the right direction?


Solution

  • Do it exactly like you would do it for a linear scale, except that you take Math.Log of your min/max values to determine the step and later do a Math.Exp to undo this transformation:

    var step = (Math.Log(maxValue) - Math.Log(minValue))/(steps - 1);
    for (var i = 0; i < steps; i++)
    {
        Console.WriteLine("{0}: {1:F0}", i + 1, Math.Exp(Math.Log(minValue) + i * step));
    }