Friday, May 6, 2011

Logarithmic slider

I have a slider with steps 0-100;

I want the range to be from 100 to 10,000,000.

I've seen some functions scattered around the net but they're all in C++; i need it in javascript.

Any ideas?

From stackoverflow
  • To get the distribution you want, I think you can use this formula:

    var value = Math.floor(-900 + 1000*Math.exp(i/10.857255959));
    

    Here's a self-contained page that will print the values you'll get for your 0-100 slider, having passed them through that formula:

    <html><body><script>
    for (var i = 0; i <= 100; i++) {
        var value = Math.floor(-900 + 1000*Math.exp(i/10.857255959));
        document.write(value + "<br>");
    }
    </script></body></html>
    

    The numbers go from 100 to 10,000,000 in what looks to my mathematically-rusty eye to be the distribution you want. 8-)

    : That worked... how did you derive it?
    RichieHindle : Started with Math.exp(i) and adjusted by hand until the numbers fit. My maths-fu is weak, but I can binary chop for England. 8-)
    Vadi : These two answers represents the power of knowledge in mathematics.. This should express to any programmer about the requirement of learning maths.
  • You can use a function like this:

    function logslider(value) {
      // value will be between 0 and 100
      var min = 0;
      var max = 100;
    
      // The result should be between 100 an 10000000
      var minv = Math.log(100);
      var maxv = Math.log(10000000);
    
      // calculate adjustment factor
      var scale = (maxv-minv) / (max-min);
    
      return Math.exp(minv + scale*(value-min));
    }
    

    The resulting values match a logarithmic scale:

    js> logslider(0);
    100.00000000000004
    js> logslider(10);
    316.22776601683825
    js> logslider(20);
    1000.0000000000007
    js> logslider(40);
    10000.00000000001
    js> logslider(60);
    100000.0000000002
    js> logslider(100);
    10000000.000000006
    
    RichieHindle : +1: So much better than my answer. 8-)

0 comments:

Post a Comment