Commit 73642cc8 authored by Erick Turricelli's avatar Erick Turricelli

ex02 completed

parent 0e45806e
#include <iostream>
#include <vector>
int main() {
int n_max = 10;
double static_array[n_max];
// static approach
int n;
std::cout << "Select the number of elements you want to insert\n";
std::cin >> n;
std::cout << "Static approach\n";
double sum = 0;
for (unsigned int i=0; i<n; i++) {
double value;
std::cin >> value;
static_array[i] = value;
sum += value;
}
// normalization
for (unsigned int i=0; i<n; i++) {
static_array[i] /= sum;
}
// print in reverse order
for (int i = n-1; i >= 0; i--) {
std::cout << static_array[i] << "\t";
}
std::cout << "\n";
// dynamic approach
std::cout << "Dynamic approach\n";
std::vector<double> vect;
double result = 0;
for(unsigned int i = 0; i < n; i++) {
double value;
std::cin >> value;
vect.push_back(value);
result += value;
}
// normalization
for (unsigned int i = 0; i < n; i++) {
vect[i] /= result;
}
// print in reverse order
for (int i = n-1; i >= 0; i--) {
std::cout << vect[i] << "\t";
}
std::cout << "\n";
return 0;
}
\ No newline at end of file
.PHONY: all
all: simpson
integration.o: integration.cpp integration.hpp
c++ -c integration.cpp
main.o: main.cpp integration.hpp
c++ -c main.cpp
simpson: main.o integration.o
c++ main.o integration.o -o simpson
library: integration.cpp
ar -crs libintegrate.a integration.o
.PHONY: clean
clean:
rm *.o simpson results.txt
\ No newline at end of file
#include <iostream>
#include <cmath>
#include <cassert>
#define _USE_MATH_DEFINES
double integration(double a, double b, int N, double (*my_func)(double x)) {
assert(N>0);
assert(b > a);
double delta = (b-a)/N;
double result = my_func(a);
for (int i = 1; i< N; i++) {
if (i%2==1) {
result += 4*my_func(a+i*delta);
}
else {
result += 2*my_func(a+i*delta);
}
}
result += my_func(b);
return result*delta/3.0;
}
double integration(double a, double b, int N, double (*my_func)(double x));
// Pre-conditions
/*
- N must be a positive integer
- b >= a
Post-conditions
- The result is the integral of the specified function in the interval [a,b]
*/
\ No newline at end of file
#include <iostream>
#include <cmath>
#include "integration.hpp"
#define _USE_MATH_DEFINES
double my_sin(double x) {
return sin(x);
}
int main() {
std::cout << "Integral of sin(x) in [0,pi] is " << integration(0.0, M_PI, 100, my_sin) << "\n";
int max_bins = 10;
std::cout << "Different bins\n";
for ( int i = 1; i < max_bins; i++) {
std::cout << i << " " << integration(0.0, M_PI, i, my_sin) << "\n";
}
return 0;
}
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment