Java 值转换整型位置到倍增序列

Java 值转换整型位置到倍增序列,java,android,math,Java,Android,Math,我有一个固定范围[0,8]的简单滑块(SeekBar) 当我更改此滑块的值时,我希望按如下方式转换这些值 [0,0.25,0.5,1,2,4,8,16,32] 时间不早了,我把自己和数学搞混了——最简单的方法是什么?我说服自己应该有一个简单的方法来使用powers(Math.pow())来完成它,但失败了很多次 编辑-我知道如何使用OnSeekBarChangeListener获取进度更新这只是我正在努力解决的实际转换算法,实现它的最简单方法是引用代码中指定的数组(如注释/其他用户所指出的):

我有一个固定范围[0,8]的简单滑块(SeekBar)

当我更改此滑块的值时,我希望按如下方式转换这些值

[0,0.25,0.5,1,2,4,8,16,32]

时间不早了,我把自己和数学搞混了——最简单的方法是什么?我说服自己应该有一个简单的方法来使用powers(Math.pow())来完成它,但失败了很多次

编辑-我知道如何使用OnSeekBarChangeListener获取进度更新这只是我正在努力解决的实际转换算法,实现它的最简单方法是引用代码中指定的数组(如注释/其他用户所指出的):

但是,如果您希望采用数学方法(基于您指定的输入/输出),则需要实现一些位移位:

public void onProgressChanged (SeekBar seekBar, int progress, boolean fromUser)
{
    // get the 'max' of our bar
    double max = (double)seekBar.getMax(); // 8
    // get the 'max' of our 'array' values, this could be a const value
    // or some other formula (like max * 4f)
    double pmax = 32;
    // get our 'mask' by shifting '1' left 'progress' times, then divide by 2
    // to get the divisor to our other formula
    double p = (double)(1 << progress) / 2; 
    // if progress == 0, then just return 0 (since that's our min)
    double val = ((progress == 0) ? 0 : (max / (pmax / p)));

    // the 'one-liner': 
    // ((double)seekBar.getMax()) / (pmax / ((double)(1 << progress) / 2)))

    System.out.format("%f%n", val);
}
public void onProgressChanged(SeekBar-SeekBar,int-progress,boolean-fromUser)
{
//获得我们酒吧的“最大值”
double max=(double)seekBar.getMax();//8
//获取“数组”值的“max”,这可能是常量值
//或者其他一些公式(如max*4f)
双pmax=32;
//将“1”向左移动“进度”次数,然后除以2,得到我们的“面具”
//得到另一个公式的除数

double p=(double)(1)您的思路是正确的,但问题确实出在0上,因为加上0的值是1。因为32是2^5,您可以使用
Math.pow(2,value-3)
,当值为0时除外,返回0。是的,这是我得到的最接近的值,但如果我每次返回到0位置时都必须手动处理一个值,因为我得到0.125,那么这仍然像是一个黑客攻击。您的分割标准是什么?参见您的示例,[0,8],然后将其除以0,Math.pow(2.0,I),其中I是介于[-2,5]之间的整数。给我你的标准。很抱歉,你在将它除以0时弄丢了我。如果使用
Math.pow()
,这是唯一的公式。我不认为这是一种黑客行为,因为不可能使用
Math.pow()
以基数2获得0。或者,只需使用
double
数组创建一个直接映射。
double[]result={0,0.25,0.5,1,2,4,8,16,32};
并使用该值作为索引:p这很有趣,但它也不像powers方法那样可维护,因为它要求您在max更改时查找或更改pmax-即如果现在有9个值,max将是64,max*4f将不起作用。是的,我同意它不可维护:)更多的人试图通过公式证明这是可能的(当然不是最简单的方法)。
public void onProgressChanged (SeekBar seekBar, int progress, boolean fromUser)
{
    // get the 'max' of our bar
    double max = (double)seekBar.getMax(); // 8
    // get the 'max' of our 'array' values, this could be a const value
    // or some other formula (like max * 4f)
    double pmax = 32;
    // get our 'mask' by shifting '1' left 'progress' times, then divide by 2
    // to get the divisor to our other formula
    double p = (double)(1 << progress) / 2; 
    // if progress == 0, then just return 0 (since that's our min)
    double val = ((progress == 0) ? 0 : (max / (pmax / p)));

    // the 'one-liner': 
    // ((double)seekBar.getMax()) / (pmax / ((double)(1 << progress) / 2)))

    System.out.format("%f%n", val);
}