Search code examples
pythonmathplotly-dashlogarithm

Python - Linear to Logarthmic Scale Conversion


Is there a way to convert number ranges?

I need to convert a linear range (0-1) to a logarithmic one (100*10^-12 - 1) so I can put a put a moveable horizontal line on a plotly plot (https://plotly.com/python/horizontal-vertical-shapes/#horizontal-and-vertical-lines-in-dash).

As far as I’m aware I can’t make my slider logarithmic to begin with (https://dash.plotly.com/dash-core-components/slider#non-linear-slider-and-updatemode).

I’ve tried normalizing. I’m not sure if that’s the right word, but basically putting my value into:

f(x) = log10(x * (max-min) + min)

Where:

x is the linear value being converted

max is the max of the log scale (1)

min is the min of the log scale (100*10^-12)

But f(.2) = .447 when I’m expecting 10*10^-9.

Is there a way accomplish this (or a better way to put a moveable horizontal line on the plot)?


Solution

  • BTW, 100*10^-12== 10^-10.

    Seems you want to take logarithm of values at 10^-10..1 range to map them into 0..1 range and vice versa?

    Y = A * log10(B * X)
    

    substituting end values:

    0 = A * log10(B * 10^-10) = A * (log10(B) - 10) 
    log10(B) = 10
    B = 10^10
    
    1 = A * log10(10^10 * 1) = A * 10
    A = 0.1
    

    So formula is

    Y = 0.1 * log10(10^10 * X) = 
        1 + 0.1 * log10(X)
    

    Reverse formula

    10*Y = log10(10^10 * X)
    10^(10*Y) = 10^10 * X
    
    X = 10^(10*Y) * 10^-10 = 
        10^(10*Y-10)
    

    using your example Y=0.2, we get X = 10^-8 as expected

    from math import log10
    for i in range(-10, 1):
        X = 10**i
        Y = 1 + 0.1 * log10(X)
        print(Y)
        print()
    
    for i in range(0, 11):
        Y = i / 10
        X  = 10**(10*Y-10)
        print(X)