Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cmath>
- #include <ctime>
- #include <iomanip>
- typedef double (*method)(double f(double), double, double, int);
- #define N_1 100
- #define N_2 1000
- using namespace std;
- double f(double x){
- return sin(4 / (x + 1)) + cos(4 * x) * cos(4 * x);
- }
- double rectangle(double f(double), double LEFT, double RIGHT, int N){
- double sq = 0, x, dx;
- dx = (RIGHT - LEFT) / N;
- for (int i = 0; i < N; i++){
- x = (RIGHT - LEFT) * (i + 1) / N;
- sq += f(x) * dx;
- }
- return sq;
- }
- double trapeze(double f(double), double LEFT, double RIGHT, int N){
- double sq = 0, x, dx;
- dx = (RIGHT - LEFT) / N;
- for (int i = 0; i < N; i++){
- x = (RIGHT - LEFT) * (i + 1) / N;
- sq += dx * (f(x) + f(x + dx)) / 2;
- }
- return sq;
- }
- double simp(double f(double), double LEFT, double RIGHT, int N){
- double sq = 0, a, b, dx;
- dx = (RIGHT - LEFT) / N;
- for (int i = 0; i < N; i++){
- a = (RIGHT - LEFT) * (i + 1) / N;
- b = a + dx;
- sq += (dx / 6) * (f(a) + f(b) + 4 * f((a + b) / 2));
- }
- return sq;
- }
- double method_time(method Method, int N){
- unsigned int start;
- double time;
- start = clock();
- for (int i = 0; i < 1000; i++){
- Method(f, 0, 2, N);
- }
- time = (clock() - start) / 1000.0;
- return time;
- }
- int main(int argc, char *argv[])
- {
- cout << "For 100:\n";
- cout << "rectangle: " << setw(6) << rectangle(f, 0, 2, N_1);
- cout << " time: " << setw(7) << method_time(rectangle, N_1) << "ms" << endl;
- cout << "trapeze: " << setw(7) << trapeze(f, 0, 2, N_1);
- cout << " time: " << setw(7) << method_time(trapeze, N_1) << "ms" << endl;
- cout << "simp: " << setw(7) << simp(f, 0, 2, N_1);
- cout << " time: " << setw(7) << method_time(simp, N_1) << "ms" << endl;
- cout << endl << endl;
- cout << "For 1000:\n";
- cout << "rectangle: " << setw(7) << rectangle(f, 0, 2, N_2);
- cout << " time: " << setw(7) << method_time(rectangle, N_2) << "ms" << endl;
- cout << "trapeze: " << setw(7) << trapeze(f, 0, 2, N_2);
- cout << " time: " << setw(7) << method_time(trapeze, N_2) << "ms" << endl;
- cout << "simp: " << setw(7) << simp(f, 0, 2, N_2);
- cout << " time: " << setw(7) << method_time(simp, N_2) << "ms" << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment