2017-08-05 10 views
2
#include<iostream> 
#include<cmath> 
using namespace std; 
double bisection(double errorVal, double userNum){ 
    double upper=userNum, lower=0; 
    double mid=(lower+upper)/2.0;; 
    while(mid*mid!=userNum){ 
     double mid=(lower+upper)/2.0; 
     if(mid*mid>userNum){ 
      upper=mid; 
     } else { 
      lower=mid; 
     } 
    } 
    return mid; 
} 

int main(){ 
    double errorVal=0, userNum=0; 
    std::cout<<"Please enter a number (larger than 0) to calculate its square root, and the desired margin of error."<<std::endl; 
    std::cin>>userNum>>errorVal; 
    bisection(errorVal,userNum); 
    std::cout<<"The calculated result is "<<bisection(errorVal,userNum)<<". The error is "<<abs(bisection(errorVal,userNum)-sqrt(userNum))<<"."<<std::endl; 
} 

これは、二分法で入力された数値の平方根を求めるために書いたプログラムです。私は2つの入力パラメータを入力しても出力が得られないので、ここで何か間違っていなければなりません。二分法で数値の平方根を見つけようとする問題

許容誤差を指定するために、errorValを正しく実装する方法も知りたいと思います。ありがとう。

+0

もう一つ: ''数(0より大きい)を入力してください、あなたは0と1の間の数字を入力しようとしています、(0,1)? – Stefan

答えて

1

エラー値は、浮動小数点演算の実行中に発生する丸めの不正確さを修正するために使用されます。

次の文はあまり真実ではないため、あなたのループは長時間続く可能性があります。

while(mid*mid==userNum) 

計算後の2つのフローティングポイントを比較する通常の方法はしたがって

fabs(x1-x2) < e //where, fabs retrieves the absolute value, 
       //x1,2 are the numbers to compare 
       //and e is the epsilon chosen. 

あり、エラー値を固定し、又は一般イプシロンと呼ばれる、同様にループを固定することになります。

double bisection(double errorVal, double userNum){ 
    double upper=userNum, lower=0; 
    double mid=(lower+upper)/2.0; 

    //error val added 
    //** fabs(mid*mid - userNum) < errorVal is true if the numers are "equal" 
    //** and you want to run the loop as long as the are NOT "equal" 
    while(!(fabs(mid*mid - userNum) < errorVal)){ 

     mid=(lower+upper)/2.0; 
     if(mid*mid>userNum){ 
      upper=mid; 
     } else { 
      lower=mid; 
     } 
    } 
    return mid; 
} 

参照:私は言及を忘れてしまった http://www.cplusplus.com/reference/cmath/fabs/

https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/

+0

助けてくれてありがとう、この問題を解決しましたが、今ではプログラムが出力として入力したものの半分を私に与えています。例:50,0.001と入力します。 0.001のエラーでsqrt(50)を表示すると仮定すると、プログラムは私に25と17.9289を出力します。 –

+1

ああ、あいまいな変数宣言があります: 'double mid'が二度定義されています。あなたはそれを取り除くべきです。コードを少し編集します。ああ、ワイルドループが間違っていた;-) – Stefan

関連する問題