Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <fstream>
- #include <iostream>
- #include <cstdlib>
- #include <vector>
- #include <string>
- using namespace std;
- void readData(const string &, vector<double> &, vector<double> &);
- double interpolation(double, const vector<double> &, const vector<double> &);
- bool isOrdered(const vector<double> &);
- void reorder(vector<double> &, vector<double> &);
- int main(){
- vector<double> a, b;
- double x = -1;
- string filename = "tunnel.dat";
- readData(filename,a,b);
- reorder(a,b);
- x = interpolation(-3.0,a,b);
- cout << endl<< x << endl;
- return 0;
- }
- void readData(const string &filename, vector<double>& a, vector<double>& b){
- ifstream file;
- double temp;
- file.open(filename);
- if(!file.is_open()){
- cout << "Error opening " << filename << endl;
- exit(1);
- }
- while(file >> temp){
- a.push_back(temp);
- file >> temp;
- b.push_back(temp);
- }
- cout << "readData success" << endl;
- }
- void reorder(vector<double>& a, vector<double>& b){
- double temp;
- for(unsigned i = 1; i < a.size(); i++){
- for(unsigned j = 0; j < (a.size() - i); j++){
- if(a.at(j) > a.at(j+1)){
- temp = a.at(j);
- a.at(j) = a.at(j+1);
- a.at(j+1) = temp;
- temp = b.at(j);
- b.at(j) = b.at(j+1);
- b.at(j+1) = temp;
- }
- }
- }
- cout << "reorder success" << endl;
- }
- bool isOrdered(const vector<double>& a){
- for(unsigned i = 0; i+1 < a.size(); i++){
- if(a.at(i) > a.at(i+1)){
- return false;
- }
- }
- return true;
- }
- double interpolation(double c, const vector<double> &a, const vector<double> &b){
- unsigned index = 1;
- while(a.at(index) < c){
- if(index >= a.size()-1){
- cout << "out of bound";
- exit(1);
- }
- if(a.at(index)==c){
- return b.at(index);
- }
- index++;
- }
- return b.at(index - 1) + ((c - a.at(index - 1))/(a.at(index) - a.at(index - 1))) * (b.at(index) - b.at(index - 1));
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement