Advertisement
Guest User

Untitled

a guest
Jan 18th, 2018
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.13 KB | None | 0 0
  1. #include <fstream>
  2. #include <iostream>
  3. #include <cstdlib>
  4. #include <vector>
  5. #include <string>
  6. using namespace std;
  7.  
  8. void readData(const string &, vector<double> &, vector<double> &);
  9. double interpolation(double, const vector<double> &, const vector<double> &);
  10. bool isOrdered(const vector<double> &);
  11. void reorder(vector<double> &, vector<double> &);
  12.  
  13. int main(){
  14. vector<double> a, b;
  15. double x = -1;
  16. string filename = "tunnel.dat";
  17. readData(filename,a,b);
  18. reorder(a,b);
  19. x = interpolation(-3.0,a,b);
  20. cout << endl<< x << endl;
  21. return 0;
  22. }
  23.  
  24. void readData(const string &filename, vector<double>& a, vector<double>& b){
  25. ifstream file;
  26. double temp;
  27. file.open(filename);
  28. if(!file.is_open()){
  29. cout << "Error opening " << filename << endl;
  30. exit(1);
  31.  
  32. }
  33. while(file >> temp){
  34. a.push_back(temp);
  35. file >> temp;
  36. b.push_back(temp);
  37. }
  38. cout << "readData success" << endl;
  39. }
  40. void reorder(vector<double>& a, vector<double>& b){
  41. double temp;
  42. for(unsigned i = 1; i < a.size(); i++){
  43. for(unsigned j = 0; j < (a.size() - i); j++){
  44. if(a.at(j) > a.at(j+1)){
  45. temp = a.at(j);
  46. a.at(j) = a.at(j+1);
  47. a.at(j+1) = temp;
  48. temp = b.at(j);
  49. b.at(j) = b.at(j+1);
  50. b.at(j+1) = temp;
  51. }
  52. }
  53. }
  54. cout << "reorder success" << endl;
  55. }
  56. bool isOrdered(const vector<double>& a){
  57. for(unsigned i = 0; i+1 < a.size(); i++){
  58. if(a.at(i) > a.at(i+1)){
  59. return false;
  60. }
  61. }
  62. return true;
  63. }
  64. double interpolation(double c, const vector<double> &a, const vector<double> &b){
  65.  
  66. unsigned index = 1;
  67.  
  68. while(a.at(index) < c){
  69. if(index >= a.size()-1){
  70. cout << "out of bound";
  71. exit(1);
  72. }
  73. if(a.at(index)==c){
  74. return b.at(index);
  75. }
  76. index++;
  77.  
  78.  
  79.  
  80. }
  81.  
  82. return b.at(index - 1) + ((c - a.at(index - 1))/(a.at(index) - a.at(index - 1))) * (b.at(index) - b.at(index - 1));
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement