Search code examples
javalogarithm

Converting linear scale to log scale in java


I looked and found one post which helped me here: Convert Linear scale to Logarithmic

However I either did some mistake I can't find or I got wrong idea of the formula. I want to convert any number from linear 1-256 range to their respective values if it was logarithmic scale. Can someone help me to correct my code? When i try values low values from zero it works kind of fine but trying to convert anything over 160 gets me result which is > 256. Here is my code:

package linear2log;

public class Linear2Log {

    public static void main(String[] args) {

        System.out.println("Ats3: " + lin2log(160));
    }

    public static long lin2log(int z) {
        int x = 1;
        int y = 256;
        double b = Math.log(y/x)/(y-x);
        double a = 10 / Math.exp(b*10);
        double tempAnswer = a * Math.exp(b*z);
        long finalAnswer = Math.max(Math.round(tempAnswer) - 1, 0);

        return finalAnswer;
    }
}

Solution

  • You get the formula wrong.

    For sure this line

    double a = 10 / Math.exp(b*10);
    

    You are using value 10 from example, but you should be using your value which is 256.

    double a = y / Math.exp(b * y);
    

    I don't get why are you using this line:

     long finalAnswer = Math.max(Math.round(tempAnswer) - 1, 0);
    

    This way you are always getting value that is one less than actual value.