C环的数值不稳定性

时间:2013-11-05 11:13:08

标签: c loops physics

我正在编写一段代码来解决电荷密度边界处的LaPlacian,它使用以下循环:

chargeold[i] = charge[i];
charge[i] = -0.05*sgn(mat[i][j])*mat[i][j]*mat[i][j];
charge[i] = (1.0 - alpha)*charge[i] + alpha*chargeold[i];
mat[i][j] = (( mat[i][j-1] + di2*mat[i][j+1] ) / ( di2 + 1.0)) + 80.0*charge[i]; 

其中,常数α是欠松弛参数0 <0。 alpha&lt; 1.这似乎没有用,我认为它可能与代码的数值不稳定性有关 - 到目前为止,我已经尝试更改常量,这里-0.05,alpha和80.0,以及各种行中的符号计算电荷和mat [i] [j]并得到截然不同的结果取决于我放的东西:例如,将最后一行的电荷系数[i]改为10.0只会导致程序被困在一个循环中,发散到无穷大或无穷大,或快速收敛到0(这是不可预期的)。这表明我创建的代码存在问题。

我也尝试将计算压缩到一行,或者在不同的行中执行相同的步骤,这些也会改变结果。

对此有任何帮助将不胜感激。感谢。

n.b。所有数据类型都是双

编辑 - 完整循环看起来像:

do
{
    sum_matdiff = 0;
    for (i = 1; i < meshno; i++)
    {

        for (j = 1; j < meshno; j++)
        {

            if (bound[i][j] == 1)   // holds boundary conditions
                continue;
            else
                matold[i][j] = mat[i][j];

            if ((i + j + count) % 2 == 1)
            {
                continue;
            }
            else if (j == (int)(0.3 * meshno))
            {                   // if statement to calculate at boundary
                chargeold[i] = charge[i];
                charge[i] = -0.05 * sgn(mat[i][j]) * mat[i][j] * mat[i][j];
                charge[i] = (1.0 - alpha) * charge[i] + alpha * chargeold[i];
                mat[i][j] =
                    ((mat[i][j - 1] + di2 * mat[i][j + 1]) / (di2 + 1.0)) +
                    80.0 * charge[i];
                if (i == 50)
                {
                    printf("%f\n", charge[50]);
                }
            }
            else
            {                   // calculates outside boundary
                omega = 1.0 / (1.0 - 0.25 * omega * rho_sq);
                mat[i][j] =
                    0.25 * (mat[i + 1][j] + mat[i - 1][j] + mat[i][j + 1] +
                            mat[i][j - 1] + (mat[i + 1][j] - mat[i - 1][j]) / (2 * i));
            }
            mat[i][j] = (1.0 - omega) * matold[i][j] + omega * mat[i][j];
            sum_matdiff += fabs(1.0 - matold[i][j] / mat[i][j]);

        }

    }

    count += 1;
    av_diff = sum_matdiff / N;

}
while (av_diff > 0.01 || count < meshno * 2);

0 个答案:

没有答案
相关问题