C統合・質問スレッド

このエントリーをはてなブックマークに追加
611デフォルトの名無しさん
>>610
細かな調整は勝手にやれ
#include <iostream>
using namespace std;

double f(double x){
double fx;
fx = cos(x) - x*x ;
return fx ;
}

double bisection(double a, double b,double (*)(double),int prc);
int main(){
double a,b;
double k;
cout << " a : " ;
cin >> a ;
cout << " b : " ;
cin >> b ;
k = bisection(a,b, f,100);
cout<<"cos(x) - x^2 := " << f(k) << " at " << k << endl;
return 0;
}
(2分法は次)
612デフォルトの名無しさん:2006/06/03(土) 11:04:35
続き

double bisection(double a, double b, double (*func)(double ),int prc){
if (func(a)*func(b) >= 0) return a; //意味ないし a で十分w
double up, lo , m;
if( func(a) > func(b) ){ up = a; lo = b ;}
else { up = b ; lo = a; }

double workprod;
int workint ;
int counter=0;

while(1){
m= (up + lo)/2;
workprod = func(m);
workint = ((int)(workprod * 1000000)); // /100.0;
if(workint==0){
cout << "counter value = "<< counter <<endl;
return m;
}
if(workint > 0) up=m;
if(workint < 0) lo=m;
counter++;
if (counter > 20000) break;
}
return 0.0;
}