二维球面波投影发生器无法正常工作

时间:2019-01-15 15:30:33

标签: java math

我制定了一种算法,使二维波在每个点处分配一个值。

线性波发生器工作正常,但不能正确生成圆波。

该算法基于for循环,该循环在彼此内部工作,分别在距中心的距离和角度上进行操作,然后使用三角函数为每个坐标生成值。

我认为问题在于算法的准确性低,尤其是角度。但是,如果我想提高此准确性,则会大大降低算法的速度。如果是这样,您能给我提供另一种算法吗?

顺便说一下,这是代码:

//f is the frequency, phase is the phase, x and y are the source coordinates
public void addCircularWave(double f, double phase, int x, int y){
    //field is the 2d array which will store the sum of all the waves
    int w = field.length;
    int h = field[0].length;

    double[][] wave = new double[w][h];

    //max finds the maximum value in the arguments
    double maxd = max(abs(w - x), abs(h - y));

    //main algorithm
    for(int dist = 0; dist < maxd; dist++){
        //i think here there is the problem
        //particularly "theta += 2*PI/720"
        //because as the distance increases it becomes less accurate.
        for(double theta = 0; theta < 2*PI; theta += 2*PI/720){
            int x0 = (int)(dist*sin(theta) + x);
            int y0 = (int)(dist*cos(theta) + y);

            //arrayoutofbounds prevention
            if(y0 < h && x0 < w && x0 > 0 && y0 > 0){
                wave[x0][y0] = sin(f*dist + phase);
            }
        }
    }

    //here the wave it's put in a map, waiting to be processed.
    cache.put(wave, new double[]{f, 0, phase, 1, x, y});
}

我期待一波干净的波浪。因此,您可以为我提供算法帮助吗,还是可以给我另一个更好的算法。

谢谢!

1 个答案:

答案 0 :(得分:0)

上面的代码太复杂了。

请记住,圆波是旋转对称的,即不需要在角度上进行迭代;幅度取决于与信号源的距离(当然还取决于频率/相位;假定您通过改变后者来模拟时间依赖性)。

只需遍历所有网格单元,然后计算它们与源的距离:

for (int i = 0; i < w; i++) {
    for (int j = 0; j < h; j++) {
        // calculate Euclidean distance to source
        double dx = i - x, dy = j - y;
        double dist = Math.sqrt(dx * dx + dy * dy);

        // no need to check bounds explicitly here
        wave[i][j] = Math.sin(f * dist + phase);
    }
}

旁注:

  • 将“频率”重命名为波矢(这不会更改代码)会更合适。

  • 与线性波不同,decay with distance是由于能量守恒而产生的。