Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Written By: Biplav Chapagain
- // Date: 2019-09-19
- // This program reads data from a .csv file and interpolates the data.
- #include <iostream>
- #include <vector>
- #include <fstream>
- #include <string>
- #include <sstream>
- using namespace std;
- struct Data
- {
- float t, x;
- };
- int size = 10;
- Data A[10];
- int read2DimData(int size) { //function to read data from a file
- ifstream ip("Prob2-2.csv");
- if (!ip.is_open()) std::cout << "ERROR: File is Open" << '\n';
- string st;
- string sx;
- float t[size];
- float x[size];
- int i=0;
- while (ip.good()&& (i < size)) {
- getline(ip, st, ',');
- getline (ip, sx, '\n');
- stringstream convertt(st);
- convertt >> t[i];
- A[i].t= t[i];
- stringstream convertx(sx);
- convertx >> x[i];
- A[i].x= x[i];
- i++;
- }
- ip.close();
- return 0;
- }
- float polynomialInterpolate(Data D[], float ti, int n) {
- float answer =0;
- for (int i=0; i < n; i++){
- float holdert = 1;
- for (int j=0; j < n; j++)
- {
- if (j!=i) {
- holdert= holdert* ((ti- (A[j].t))/((A[i].t)-(A[j].t)));
- }
- }
- answer= answer+ holdert* A[i].x;
- //cout << answer<< endl;
- }
- return answer;
- }
- int main() {
- float t;
- int check=0;
- float answer;
- read2DimData(size);
- cout << "The Data read from the file is below: " << endl;
- for (int i =0; i < size; i++) {
- cout <<A [i].t<< " , "<< A [i].x << endl ;
- }
- cout << ""<< endl;
- cout << "Enter the value of t you wish to calculate" << endl;
- while (check ==0){
- check =1;
- cin >> t;
- if ((t < A[0].t) || (t > A[size-1].t)) {
- cout << "Please enter a value of t within [" << A[0].t << " , " << A[size-1].t << "]" << endl;
- check =0;
- }
- }
- answer = polynomialInterpolate(A, t, size);
- cout << "The value of x corresponding to t= " << t << " is: "<< answer << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement