Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // ConsoleApplication9.cpp : 定義主控台應用程式的進入點。
- //
- #include "stdafx.h"
- #include <iostream>
- #include <iomanip>
- #include <math.h>
- using namespace std;
- class axn {
- public:
- axn() {
- //cout << "inside\t" << "建立了一個項" << endl;
- }
- void set(double ina, double inn) {
- a = ina;
- n = inn;
- //cout << "inside\t" << "設定了一個項為" << a << "x^" << n << endl;
- }
- double df(double x) {
- //cout << "inside\t" << "一次微分了" << a << "x^" << n << endl;
- return pow(x, n - 1)*n*a;
- }
- double f(double x) {
- //cout << "inside\t" << "一次微分了" << a << "x^" << n << endl;
- return pow(x, n )*a;
- }
- double getdfa() {
- return a*n;
- }
- double getdfn() {
- return n-1;
- }
- double ddf(double x) {
- return pow(x, n - 2)*n*(n - 1)*a;
- }
- double geta() {
- return a;
- }
- double getn() {
- return n;
- }
- private:
- double n;
- double a;
- };
- class sumaxn {
- public:
- int i;
- axn *arr;
- sumaxn(double ai[], double ni[]) {
- int k = 0;
- while (ni[k] != -50) {
- k++;
- }
- i = k;
- //cout << "inside\t\t" << "建立了一個" << i << "項的項之和" << endl;
- arr = new axn[i];
- for (int j = 0; j<i; j++) {
- arr[j].set(ai[j], ni[j]);
- }
- }
- sumaxn getdf() {
- double *dadate = new double[i];
- double *dndate = new double[i];
- for (int j = 0; j < i; j++) {
- dadate[j] = arr[j].getdfa();
- dndate[j] = arr[j].getdfn();
- }
- //cout << "inside\t\t" << "微分多項式" << endl;
- dadate[i] = -50;
- dndate[i] = -50;
- sumaxn df(dadate, dndate);
- //cout << "inside\t\t" << "微分多項式";
- //df.pp();
- return df;
- }
- double getdf(double x) {
- double tot=0;
- for (int j = 0; j < i; j++) {
- tot += arr[j].df(x);
- }
- return tot;
- }
- double getf(double x) {
- double tot = 0;
- for (int j = 0; j < i; j++) {
- tot += arr[j].f(x);
- }
- return tot;
- }
- void pp() {
- for (int j = 0; j<i; j++) {
- cout <<arr[j].geta() << "x^" << arr[j].getn() <<(j==(i-1)?"":"+");
- }
- cout << endl;
- }
- };
- int main(int argc, char** argv) {
- double adate[] = { 2,1,3,4,4,4,-50};
- double ndate[] = { 5,8,3,2,1,0,-50};
- sumaxn f(adate, ndate);
- cout << "原方程式為:";
- f.pp();
- cout << "一次微分後的方程式為:";
- f.getdf().pp();
- double a = 10;
- for (int i = 0; i < 100; i++) {
- a = a - f.getf(a) / f.getdf().getf(a);
- }
- cout << "牛頓法求y=0的解x為" << setprecision(20) << a;
- system("pause");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement