Advertisement
Guest User

Untitled

a guest
Sep 19th, 2019
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.85 KB | None | 0 0
  1. // Written By: Biplav Chapagain
  2. // Date: 2019-09-19
  3. // This program reads data from a .csv file and interpolates the data.
  4. #include <iostream>
  5. #include <vector>
  6. #include <fstream>
  7. #include <string>
  8. #include <sstream>
  9.  
  10.  
  11. using namespace std;
  12. struct Data
  13. {
  14. float t, x;
  15. };
  16.  
  17. int size = 10;
  18. Data A[10];
  19.  
  20. int read2DimData(int size) { //function to read data from a file
  21. ifstream ip("Prob2-2.csv");
  22. if (!ip.is_open()) std::cout << "ERROR: File is Open" << '\n';
  23. string st;
  24. string sx;
  25. float t[size];
  26. float x[size];
  27. int i=0;
  28.  
  29. while (ip.good()&& (i < size)) {
  30. getline(ip, st, ',');
  31. getline (ip, sx, '\n');
  32. stringstream convertt(st);
  33. convertt >> t[i];
  34. A[i].t= t[i];
  35. stringstream convertx(sx);
  36. convertx >> x[i];
  37. A[i].x= x[i];
  38. i++;
  39. }
  40. ip.close();
  41. return 0;
  42. }
  43.  
  44. float polynomialInterpolate(Data D[], float ti, int n) {
  45. float answer =0;
  46. for (int i=0; i < n; i++){
  47. float holdert = 1;
  48. for (int j=0; j < n; j++)
  49. {
  50. if (j!=i) {
  51. holdert= holdert* ((ti- (A[j].t))/((A[i].t)-(A[j].t)));
  52. }
  53. }
  54.  
  55. answer= answer+ holdert* A[i].x;
  56. //cout << answer<< endl;
  57. }
  58. return answer;
  59. }
  60.  
  61. int main() {
  62. float t;
  63. int check=0;
  64. float answer;
  65. read2DimData(size);
  66. cout << "The Data read from the file is below: " << endl;
  67. for (int i =0; i < size; i++) {
  68. cout <<A [i].t<< " , "<< A [i].x << endl ;
  69. }
  70. cout << ""<< endl;
  71. cout << "Enter the value of t you wish to calculate" << endl;
  72. while (check ==0){
  73. check =1;
  74. cin >> t;
  75. if ((t < A[0].t) || (t > A[size-1].t)) {
  76. cout << "Please enter a value of t within [" << A[0].t << " , " << A[size-1].t << "]" << endl;
  77. check =0;
  78. }
  79. }
  80. answer = polynomialInterpolate(A, t, size);
  81. cout << "The value of x corresponding to t= " << t << " is: "<< answer << endl;
  82.  
  83. return 0;
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement