1
#include<stdio.h>
#include<stdlib.h>
#define abs(a) ((a)>0 ? a: -a)
#define eps_sqrt 0.00000000000001
#define it 100

float sqrt(float x)
/*The Square Root Function using the Newton's Method*/
{
    int it_sqrt=0;
    float a_sqrt = x/2;
    while ((abs((a_sqrt*a_sqrt)-(x))>=eps_sqrt) && (2.0*a_sqrt != 0) && (it_sqrt<=it))
    {
        a_sqrt = a_sqrt - ((a_sqrt*a_sqrt)-(x)/(2.0*a_sqrt));
        it_sqrt++;
    }
    return a_sqrt;
}

int main()
{
    printf("%.5f\n", sqrt(5));
    system ("pause");
}

ニュートンの反復法を使用してPythonで平方根を見つけようとしましたが、完全にうまく機能しました。私はCを初めて使用しますが、この関数が機能しなかった理由がわかりません。私がそれを実行するときはいつでも、それは「-1。#INF0A」を返します。どんな助けでもありがたいです。


編集:私はepsをに変更しようとしましたが0.000001、それも機能しませんでした。

4

4 に答える 4

4

この行を変更する:

                a_sqrt = a_sqrt - ((a_sqrt*a_sqrt)-(x)/(2.0*a_sqrt));

                a_sqrt = a_sqrt - ((a_sqrt*a_sqrt - x)/(2.0*a_sqrt));

私のために働きます。

于 2012-05-03T16:09:02.003 に答える
3

より大きなイプシロンを使用してみてください。Pythonはfloatの代わりにdoubleを使用している可能性があります。

于 2012-05-03T16:04:29.100 に答える
2

doubleこれは、実際に使用することが理にかなっているまれなケースの1つです。floatの精度はeps_sqrtよりも大幅に低いことに注意してください。

[mic@mic-nb tmp]$ cat tmp2.c
#include <stdio.h>
#include <math.h>

int main() {
    double a = sqrtl(2.0);
    printf("%1.20f\n", a - (float) a);
}
[mic@mic-nb tmp]$ gcc tmp2.c; ./a.out
0.00000002420323430563
vs. your value of:
0.00000000000001

したがって、ほとんどの場合、プログラムは終了しません。

于 2012-05-03T16:37:10.637 に答える
2
double mysqrt(double x){
    double eps=pow(10,-10);
    double x0 = 0.0;
    double x1 = x/2.0;
    while(fabs(x1 - x0)>eps){
        x0 = x1;
        x1 = x0 + (x - x0*x0)/x0/ 2.0;
    }
    return x1;
}

マクロ拡張
abs((a_sqrt*a_sqrt)-(x))
拡張(((a_sqrt*a_sqrt)-(x))>0 ? (a_sqrt*a_sqrt)-(x): -(a_sqrt*a_sqrt)-(x))
NG:-(a_sqrt*a_sqrt)-(x)

abs((a_sqrt*a_sqrt- x))
拡張(((a_sqrt*a_sqrt- x))>0 ? (a_sqrt*a_sqrt- x): -(a_sqrt*a_sqrt- x))

に書き直し
#define abs(a) ((a)>0 ? a: -a)
ます
#define abs(a) ((a)>0 ? a: -(a))

于 2012-05-03T16:50:10.640 に答える