- 最後登錄
- 2023-5-26
- 在線時間
- 0 小時
- 註冊時間
- 2011-9-22
- 閱讀權限
- 50
- 精華
- 0
- UID
- 10339933
- 帖子
- 7565
- 積分
- 4321 點
- 潛水值
- 34960 米
| 若對尊貴或贊助會員有任何疑問,歡迎向我們查詢。我們的即時通或MSN: admin@eyny.com liforlove 發表於 2013-6-23 06:19 PM
可以是可以了
只不過答案跟原本的似乎不太一樣...左邊為C++版本 右邊為原版 - #include <cstdlib>
- #include <iostream>
- #include <cmath>
- class NewtonRoot {
- private:
- double x0, x1, eps, max_itera;
- public:
- NewtonRoot(double x0, double x1, double eps, int max_itera)
- { this->x0 = x0; this->x1 = x1; this->eps = eps; this->max_itera = max_itera; };
- ~NewtonRoot() { };
- double DiffResult();
- double DiffmResult();
- double XnResult();
- double func(double x);
- };
- double NewtonRoot::func(double x)
- {
- double t = x-1.235;
- return pow(t, 5.0);
- }
- // -------------------------------------------------------
- double NewtonRoot::DiffResult(void)
- {
- double y0= this->func(this->x0), y1;
- double diff, x2;
- double x1t, x0t;
- int i=0;
-
- x0t=this->x0;
- x1t=this->x1;
-
- do{
- y1=this->func(x1t);
- diff = (y1 - y0) / (x1t - x0t);
- x2 = x1t - y1 / diff;
- x0t = x1t;
- y0 = y1;
- x1t = x2;
- ++i;
- }while(fabs(x1t-x0t)>this->eps && i<this->max_itera);
- print_f("> times: %4d , ", i);
- return x2;
- }
- // -------------------------------------------------------
- double NewtonRoot::DiffmResult(void)
- {
- const int m = 5;
- double y0 = this->func(this->x0), y1;
- double diff, x2;
- double x0t, x1t;
- int i=0;
-
- x0t = this->x0;
- x1t = this->x1;
-
- do{
- y1=this->func(x1t);
- diff = (y1 - y0) / (x1t - x0t);
- x2 = x1t - m * y1 / diff;
- x0t = x1t;
- y0 = y1;
- x1t = x2;
- ++i;
- }while(fabs(x1t-x0t)>this->eps && i<this->max_itera);
- print_f("> times: %4d , ", i);
- return x2;
- }
- // -------------------------------------------------------
- double NewtonRoot::XnResult(void)
- {
- double y0 = this->func(this->x0), y1;
- double diff, x2, delta;
- double rate=1.0;
- double x0t, x1t;
- int i=0;
- x0t = this->x0;
- x1t = this->x1;
- srand(time(NULL));
- do{
- delta = y1 = this->func(x1t);
- // if(fabs(y1) < fabs(y0)) rate=1.0;
- // else if(rate > 5E-5) rate*=0.5;
- rate = 5.0 * rand() / RAND_MAX; // more faster
- diff = (y1 - y0) / (x1t - x0t);
- x2 = x1t - rate * y1 / diff;
- x0t = x1t; y0 = y1; x1t = x2;
- ++i;
- }while(fabs(delta)>this->eps && i<this->max_itera);
- print_f("> times: %4d , ", i);
- return x2;
- }
- int main()
- {
- const double eps=1E-9;
- const int max_iterator=1000;
- double x, low, up;
- low = -10.0, up = low + 1.0;
- class NewtonRoot *n = new NewtonRoot(low, up, eps, max_iterator);
- x = n->DiffResult();
- print_f("NewtonRoot.Diff func(%+.15e) = %+.15e\n", x, n->func(x));
- x = n->XnResult();
- print_f("NewtonRoot.Xn func(%+.15e) = %+.15e\n", x, n->func(x));
- x = n->DiffmResult();
- print_f("NewtonRoot.Diffm func(%+.15e) = %+.15e\n", x, n->func(x));
-
- system("PAUSE");
-
- delete n;
-
- return EXIT_SUCCESS;
- }
複製代碼 我用這個版本試
都很正常耶...
|
|