double Polynomial_Root(int n,double c[], double a, double b, double eps){ int newton(double x0, double *r,double c[], double d[], int n, double a, double b, double eps); double d[MAXN]; int i; double root = 0.0; for (i=n-1; i>=0; i--) { d[i] = (i+1)*c[i+1]; } if (a>b) { root = a; a = b; b = root; } double average = 0.0; int k = 0; int t = newton(a, &root, c, d, n, a, b, eps); if (t == 1){ average += root; k++; } int s = newton(b, &root, c, d, n, a, b, eps); if (s == 1){ average += root; k++; } int u = newton((a+b)*0.5, &root, c, d, n, a, b, eps); if (u == 1){ average += root; k++; } average /= k; if (fabs(root)<eps) return fabs(root); else return root; }
int newton(int n, int k) { if (k == 0 || k == n) return 1; else return newton(n - 1, k - 1) + newton(n - 1, k); }
int newton(int n,int k) { if(k==0 || k==n) return 1; if(k>0 && k<n) return newton(n-1,k-1)+newton(n-1,k); }
void main_train(int iter,void* dat,void *vector){ printf("starting train\n"); Data data; int t; //init constant do{ Int* buffer=(Int*)dat; dat+=sizeof(Int)*3; data.ndata=buffer[0]; data.cust.n=buffer[1]; data.movie.n=buffer[2]; data.ndim=10; data.cust.p=(Int*)dat; dat+=sizeof(Int)*(data.cust.n+1); data.movie.p=(Int*)dat; dat+=sizeof(Int)*(data.movie.n+1); data.cust.i=(Int*)dat; dat+=sizeof(Int)*data.ndata; data.movie.i=(Int*)dat; dat+=sizeof(Int)*data.ndata; }while(0); printf("(ndata: %d)(ncust: %d)(nmovie: %d)\n",data.ndata,data.cust.n,data.movie.n); //data.ndata=10000000; for(t=0;t<10;t++){ printf("p2[%d]=%d\n",t,data.movie.p[t]); } if(vector==0){ int size=(data.cust.n+data.movie.n)*data.ndim; vector=malloc(sizeof(Double)*size); for(size--;size>=0;size--){ ((Double*)vector)[size]=((Double)rand()/RAND_MAX-0.5)/10; } } //init vector Double* v1=(Double*)vector; vector+=sizeof(Double)*data.cust.n*data.ndim; Double* v2=(Double*)vector; vector+=sizeof(Double)*data.cust.n*data.ndim; printf("starting iteration\n"); time_t time0,time1; time(&time0); int iterleft=iter; while(iterleft!=0){ newton(v1,v2,data,data.cust,data.movie); request_judge(v1); newton(v2,v1,data,data.movie,data.cust); request_judge(v1); printf("iterleft: %d\n",iterleft); time(&time1); printf("time elapsed: %lu\n",time1-time0); iterleft--; } }
int main(void) { double a1 = 0.0, b1 = 1.0; double a2 = 1.0, b2 = 3.0; double eps = 0.000001; double d1 = dichotomy(f1, eps, a1, b1); double i1 = iteration(f1_it, eps, a1, b1); double n1 = newton(f1, f1_pr, eps, a1, b1); double d2 = dichotomy(f2, eps, a2, b2); double i2 = iteration(f2_it, eps, a2, b2); double n2 = newton(f2, f2_pr, eps, a2, b2); printf("Точность: %.6f\n", eps); printf("+-----------+----------+---------------+-----------------------+-----------+----------+---------+\n"); printf("| Уравнение | Отрезок | Базовый метод | Прибл. значение корня | Дихотомии | Итераций | Ньютона |\n"); printf("+-----------+----------+---------------+-----------------------+-----------+----------+---------+\n"); printf("| 1 | [0, 1] | Ньютона | 0.8814 |%.9f|%.8f|%.7f|\n", d1, i1, n1); printf("+-----------+----------+---------------+-----------------------+-----------+----------+---------+\n"); printf("| 2 | [1, 3] | Дихотомии | 1.3749 |%.9f| - |%.7f|\n", d2, n2); printf("+-----------+----------+---------------+-----------------------+-----------+----------+---------+\n"); return 0; }
int newton(int n, int k) { if (n == 0 || n == k) { return 1; } if (n > 0 && k > 0 && n > k) { return newton(n - 1, k - 1) + newton(n - 1, k); } }
int newton(int n,int k) { if(k==0 || k==n) { return 1; } if(n>k && k>0) { return newton(n-1,k-1)+newton(n-1,k); } }
void CtcNewton::contract(IntervalVector& box, ContractContext& context) { if (!(box.max_diam()<=ceil)) return; else { if (!vars) newton(f,box,prec,gauss_seidel_ratio); else newton(f,*vars,box,prec,gauss_seidel_ratio); } if (box.is_empty()) { context.output_flags.add(FIXPOINT); } }
int main() { // Create coarse mesh, set Dirichlet BC, enumerate // basis functions Mesh *mesh = new Mesh(A, B, N_elem, P_init, N_eq); mesh->set_bc_left_dirichlet(0, Val_dir_left_0); mesh->set_bc_right_dirichlet(0, Val_dir_right_0); mesh->set_bc_left_dirichlet(1, Val_dir_left_1); mesh->set_bc_right_dirichlet(1, Val_dir_right_1); printf("N_dof = %d\n", mesh->assign_dofs()); // Register weak forms DiscreteProblem *dp = new DiscreteProblem(); dp->add_matrix_form(0, 0, jacobian_0_0); dp->add_matrix_form(0, 1, jacobian_0_1); dp->add_matrix_form(1, 0, jacobian_1_0); dp->add_matrix_form(1, 1, jacobian_1_1); dp->add_vector_form(0, residual_0); dp->add_vector_form(1, residual_1); // Newton's loop newton(dp, mesh, NULL, NEWTON_TOL, NEWTON_MAXITER); // Plot the solution Linearizer l(mesh); l.plot_solution("solution.gp"); printf("Done.\n"); return 1; }
int main() { // Create coarse mesh, set Dirichlet BC, enumerate // basis functions Mesh *mesh = new Mesh(A, B, N_elem, P_init, N_eq); printf("N_dof = %d\n", mesh->assign_dofs()); // Register weak forms DiscreteProblem *dp = new DiscreteProblem(); dp->add_matrix_form(0, 0, jacobian_vol); dp->add_vector_form(0, residual_vol); dp->add_matrix_form_surf(0, 0, jacobian_surf_left, BOUNDARY_LEFT); dp->add_vector_form_surf(0, residual_surf_left, BOUNDARY_LEFT); dp->add_matrix_form_surf(0, 0, jacobian_surf_right, BOUNDARY_RIGHT); dp->add_vector_form_surf(0, residual_surf_right, BOUNDARY_RIGHT); // Newton's loop newton(dp, mesh, NULL, NEWTON_TOL, NEWTON_MAXITER); // Plot the solution Linearizer l(mesh); l.plot_solution("solution.gp"); printf("Done.\n"); return 1; }
void main () { double x[2], fx[2], tol; int iter, maxIter; // INPUT cout << "Enter tolerance: "; cin >> tol; cout << "Enter max iterations: "; cin >> maxIter; cout << "Enter an initial guess: "; cin >> x[0] >> x[1]; // NEWTON SOLVER int state = newton(x, f, df, iter, tol, maxIter); f(x,fx); // STATUS AND OUTPUT switch(state) { case SUCCESS: cout << "An approximate root is (" << x[0] << ", " << x[1] <<")\n"; cout << "f(approximate root) is (" << fx[0] << ", " << fx[1] <<")\n"; cout << "The number of iterations is " << iter << endl; break; case WONT_STOP: default: cout << "ERROR: Failed to converge in "<<maxIter<<" iterations!" << endl; break; } }
void NewtonEqualitySelfTest() { cout<<"Testing equality-constrained Newton solver..."<<endl; Matrix A(2,2); Vector b(2); Real c; A.setIdentity(); A *= -Two; b.setZero(); c=10; QuadraticScalarFieldFunction c1(A,b,c); ComponentVectorFieldFunction C; C.functions.resize(1); C.functions[0] = &c1; Vector p(2); p(0) = -1; p(1) = 0; Real q=0; LinearScalarFieldFunction f(p,q); NonlinearProgram nlp(&f,&C); nlp.minimize = true; nlp.inequalityLess = false; NewtonSolver newton(nlp); newton.x.resize(2); newton.x(0) = -1; newton.x(1) = -1; newton.verbose=1; newton.Init(); int iters=100; ConvergenceResult res=newton.Solve(iters); cout<<"Result "<<res<<" iters "<<iters<<endl; cout<<"x = "<<VectorPrinter(newton.x)<<endl; cout<<"done."<<endl; }
void OGProjection<Scalar>::project_internal(Hermes::vector<Space<Scalar>*> spaces, WeakForm<Scalar>* wf, Scalar* target_vec, Hermes::MatrixSolverType matrix_solver_type) { _F_; // Instantiate a class with global functions. Global<Scalar> hermes2d; unsigned int n = spaces.size(); // sanity checks if (n <= 0 || n > 10) error("Wrong number of projected functions in project_internal()."); for (unsigned int i = 0; i < n; i++) if(spaces[i] == NULL) error("this->spaces[%d] == NULL in project_internal().", i); if (spaces.size() != n) error("Number of spaces must match number of projected functions in project_internal()."); // this is needed since spaces may have their DOFs enumerated only locally. int ndof = Space<Scalar>::assign_dofs(spaces); // Initialize DiscreteProblem. DiscreteProblem<Scalar> dp(wf, spaces); // Initial coefficient vector for the Newton's method. Scalar* coeff_vec = new Scalar[ndof]; memset(coeff_vec, 0, ndof*sizeof(Scalar)); // Perform Newton's iteration. NewtonSolver<Scalar> newton(&dp, matrix_solver_type); if (!newton.solve(coeff_vec)) error("Newton's iteration failed."); delete [] coeff_vec; if (target_vec != NULL) for (int i = 0; i < ndof; i++) target_vec[i] = newton.get_sln_vector()[i]; }
int main() { double a, b, e; int status; char chce_podac_x[2]; do { printf("Podaj a: "); scanf("%lf", &a); printf("Podaj b: "); scanf("%lf", &b); if(a < b) { if (f(a) * f(b) < 0) { do { printf("Podaj przybliżenie: "); status = scanf("%lf", &e); if(e > 0 && e < 1) { bisection(a, b, e); newton(a, e); } do { printf("Chcesz podać kolejne przybliżenie? (tak/nie): "); scanf("%s", chce_podac_x); if(strcmp(chce_podac_x, "tak") == 0 || strcmp(chce_podac_x, "nie") == 0) break; } while(1); } while (strcmp(chce_podac_x, "tak") == 0); } else { printf("błąd: f(a) i f(b) muszą mieć różny znak\n"); } } else { printf("błąd: a musi być mniejsze od b\n"); } } while(a >= b || f(a) * f(b) >= 0); return 0; }
int main() { printf("\n Dla równania f(x) = 0, gdzie f(x) = 3x + 2 - e^x, wczytać a, b należące"); printf("\n do zbioru liczb rzeczywistych takie, by a < b oraz f(a) * f(b) < 0. Następnie,"); printf("\n dopóki \"użytownik się nie znudzi\", wczytywać wartości 0 < E < 1 i metodą"); printf("\n połowienia na [a, b] przybliżyc z dokładnością E rozwiązanie tego równania."); printf("\n Rozwiązanie to przybliżyc również metodą Newtona z x_0 = a, przy czym, x_k"); printf("\n będzie dobrym przybliżeniem, gdy |x_k - x_(k - 1)| <= E. Porównać ilość"); printf("\n kroków wykonanych metodą połowienia i metodą Newtona.\n"); double a, b; printf("\n Podaj a należące do zbioru liczb rzeczywistych:\n a = "); scanf("%lf", &a); b = a; while(a >= b || equation(a) * equation(b) >= 0) { printf("\n Podaj b należące do zbioru liczb rzeczywistych,\n takie by b > a oraz f(b) * f(a) < 0\n b = "); scanf("%lf", &b); } double epsilon, rB, rN; int choice; while (1) { printf("\n 1 - Przybliż rozwiązanie równania z dokładnością E metodą połowienia i Newtona"); printf("\n 2 - Zakoncz program"); printf("\n Twoj wybor: "); scanf("%i", &choice); switch (choice) { case 1: epsilon = 0; while (epsilon <= 0 || epsilon >= 1) { printf("\n Podaj E, takie by 0 < E < 1:\n E = "); scanf("%lf", &epsilon); } rB = bisection(a, b, epsilon); rN = newton(a, epsilon); printf("\n Metoda połowienia:\n %lf - przybliżone rozwiązanie\n %i - ilość kroków\n", rB, iB); printf("\n Metoda Newtona:\n %lf - przybliżone rozwiązanie\n %i - ilość kroków\n", rN, iN); iB = iN = 0; break; case 2: printf("\n"); return 0; } } }
int main() { double x_0; /* Initial guess */ double x; /* Approximate solution */ double tol; /* Maximum error */ int max_iters; /* Maximum number of iterations */ int iters; /* Actual number of iterations */ int converged; /* Whether iteration converged */ printf("Enter x_0, tol, and max_iters\n"); scanf("%lf %lf %d", &x_0, &tol, &max_iters); x = newton(x_0, tol, max_iters, &iters, &converged); if (converged) { printf("Newton algorithm converged after %d steps.\n", iters); printf("The approximate solution is %19.16e\n", x); printf("f(%19.16e) = %19.16e\n", x, f(x)); } else { printf("Newton algorithm didn't converge after %d steps.\n", iters); printf("The final estimate was %19.16e\n", x); printf("f(%19.16e) = %19.16e\n", x, f(x)); } return 0; } /* main */
int main() { newton(); //--gnuplotによるグラフ作成--// FILE *gp; gp=popen("gnuplot -persist","w"); fprintf(gp, "set title 'df(x)=-1/x^2+1/x'\n"); fprintf(gp, "set size ratio 1.0\n"); fprintf(gp, "set border lw 2.5\n"); fprintf(gp, "set mxtics 5\n"); fprintf(gp, "set mytics 5\n"); fprintf(gp, "set nokey\n"); fprintf(gp, "set xl 'x' font 'Arial'\n"); fprintf(gp, "set yl 'df(x)' font 'Arial'\n"); fprintf(gp, "set parametric\n"); fprintf(gp, "const=0\n"); fprintf(gp, "set trange[-5:5]\n"); fprintf(gp, "set xr [0:5]\n"); fprintf(gp, "set yr [-5:1]\n"); fprintf(gp, "plot const+1.5,t dt(5,5) lw 2.5 lt 1 lc rgb 'black'\n"); fprintf(gp, "replot t,const dt(5,5) lw 2.5 lt 1 lc rgb 'black'\n"); fprintf(gp, "replot t,t*4/27 dt(5,5) lw 2.5 lt 1 lc rgb 'navy'\n"); fprintf(gp, "replot t,-1/(t*t)+1/t w l lw 3 lt 1 lc rgb 'red'\n"); pclose(gp); //--gnuplot終了--// return 0; }
void CtcNewton::contract(IntervalVector& box) { if (!(box.max_diam()<=ceil)) return; else newton(f,box,prec,gauss_seidel_ratio); if (box.is_empty()) { set_flag(FIXPOINT); } }
int main(void){ double x; double eps=pow(2.0,-30.0); printf("Please input x0:"); scanf("%lf",&x); newton(x,eps); return 0; }
int inexact_newton(int , char **) { typedef double value_type; typedef std::string key_type; typedef std::map<key_type,std::vector<value_type> > stats_type; stats_type stats; const int size = 2; InexactNewtonMethod<value_type,1000,100> newton(size); function_type<2> F; value_type x[size] = {1,1}; newton ( F,x,1e-16f,1e-13f, &stats ); display_stats(stats); return 0; }
int main() { printf("%d\n",newton(15,8)); }
int main() { mpc mycase = loadcase(); //mycase.print(); newton(mycase); return 0; }
bool PicardSolver<Scalar>::solve(double tol, int max_iter) { int it = 0; NewtonSolver<Scalar> newton(static_cast<DiscreteProblem<Scalar>*>(this->dp), this->matrix_solver_type); while (true) { // Delete the old solution vector, if there is any. if(this->sln_vector != NULL) { delete [] this->sln_vector; this->sln_vector = NULL; } // Project the previous solution in order to get a vector of coefficient. this->sln_vector = new Scalar[static_cast<DiscreteProblem<Scalar>*>(this->dp)->get_space(0)->get_num_dofs()]; memset(this->sln_vector, 0, static_cast<DiscreteProblem<Scalar>*>(this->dp)->get_space(0)->get_num_dofs() * sizeof(Scalar)); // Perform Newton's iteration to solve the linear problem. // Translate the resulting coefficient vector into the Solution sln_new. Solution<Scalar> sln_new; if (!newton.solve(this->sln_vector, tol, max_iter)) { warn("Newton's iteration in the Picard's method failed."); return false; } else Solution<Scalar>::vector_to_solution(newton.get_sln_vector(), static_cast<DiscreteProblem<Scalar>*>(this->dp)->get_space(0), &sln_new); double rel_error = Global<Scalar>::calc_rel_error(sln_prev_iter, &sln_new, HERMES_L2_NORM); if (this->verbose_output) info("---- Picard iter %d, ndof %d, rel. error %g%%", it+1, static_cast<DiscreteProblem<Scalar>*>(this->dp)->get_space(0)->get_num_dofs(), rel_error); // Stopping criterion. if (rel_error < tol) { for (int i = 0; i < static_cast<DiscreteProblem<Scalar>*>(this->dp)->get_space(0)->get_num_dofs(); i++) this->sln_vector[i] = newton.get_sln_vector()[i]; return true; } if (it++ >= max_iter) { if (this->verbose_output) info("Maximum allowed number of Picard iterations exceeded, returning false."); return false; } // Copy the solution into the previous iteration. sln_prev_iter->copy(&sln_new); } }
inline long long int solve(const long long int &n, const long long int &k) { long long int result = 0; std::sort(number, number + numbers); for(long long int i = 1; i <= n - k + 1; ++ i) result = (result + number[numbers - i] * newton(n - i, k - 1)) % MOD; return result; }
int main() { /* * Вычисляем ширину эпсилон. */ int epswidth = ceil(-log10(REAL_EPSILON)); printf( "target_1 = 0, x = %.*f; dichotomy, x ∈ [%f, %f]\n", epswidth, dichotomy(target_1, TARGET_1_A, TARGET_1_B), TARGET_1_A, TARGET_1_B ); printf( "target_1 = 0, x = %.*f; iterations, x ∈ [%f, %f]\n", epswidth, iterations(target_1_xfx, TARGET_1_A, TARGET_1_B), TARGET_1_A, TARGET_1_B ); printf( "target_1 = 0, x = %.*f; newton, x ∈ [%f, %f]\n", epswidth, newton(target_1, target_1_derivative, TARGET_1_A, TARGET_1_B), TARGET_1_A, TARGET_1_B ); printf( "target_2 = 0, x = %.*f; dichotomy, x ∈ [%f, %f]\n", epswidth, dichotomy(target_2, TARGET_2_A, TARGET_2_B), TARGET_2_A, TARGET_2_B ); printf( "target_2 = 0, x = %.*f; iterations, x ∈ [%f, %f]\n", epswidth, iterations(target_2_xfx, TARGET_2_A, TARGET_2_B), TARGET_2_A, TARGET_2_B ); printf( "target_2 = 0, x = %.*f; newton, x ∈ [%f, %f]\n", epswidth, newton(target_2, target_2_derivative, TARGET_2_A, TARGET_2_B), TARGET_2_A, TARGET_2_B ); return (0); }
main() { double user_number; printf("Please enter the number you want the square root of\r\n"); scanf("%lf",&user_number); //squareroot(user_number); newton(user_number); }
int main() { double x; double a = 0.0; for (int i=0; i<100000; i++) { x = newton(i % 10); a += x; // cout << x << endl; } printf("%g\n", a); }
int main() { FILE *file = fopen("result/newtonDROB.txt", "w+"); for (i=0; i < 5; i++) { printf("Iteration %d with e = %lf\n", i+1, e[i]); newton(file); } fclose (file); return 0; }
int main() { int n, k, out; printf("Podaj wartość n: "); scanf("%d", &n); printf("Podaj wartość k: "); scanf("%d", &k); wynik = newton(n, k); printf("%d\n", out); }
int main(void) { int x, y; printf("Podaj liczbe x: "); scanf("%d", &x); printf("Podaj liczbe y: "); scanf("%d", &y); printf("%d \n", newton(x, y)); return 0; }