1

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;
    }
}
Haruki
  • 109
  • 1
  • 10
  • This is almost certainly an `int` maths error. Changing all your `int`s to `double` should solve your problem. – OldCurmudgeon Dec 08 '17 at 11:05
  • For values x and y given in example this is not the case. It could be the problem for other values. This line is potentially dangerous: double b = Math.log(y/x)/(y-x); – Luk Dec 08 '17 at 11:59

1 Answers1

1

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.

Luk
  • 2,186
  • 2
  • 11
  • 32
  • oh thanks, I fixed that line, apparently it was a culprit. I want to get values from 0 to 255 for RGB, but i cant plug 0 to (y/x) that's why i subtract 1 later on. My function is to be used to basically manipulate one color channel. – Haruki Dec 08 '17 at 12:26