Problem C: Piecewise Linear Interpolation (20 points Sometimes time-dependent da
ID: 3891586 • Letter: P
Question
Problem C: Piecewise Linear Interpolation (20 points Sometimes time-dependent data that is gathered at irregular times needs to be estimated at more regular times. For example, a remote sensor's readings might occur only at cer- tain times t-0.0, .12. .25, .37, .50, .71, 1.0 when what you want is readings at times 0.0, 0.1. 0.2, 0.3, have been is to use piecewise linear interpolation.3 For example, suppose we want to esti- rnate what the reading would have been at time t = 0.2. Let / 12) be the reading at time t12, and f (.25) be the reading at time t-.25. The time0.2 is 8/13 of the way from .12 to .25, so we can estimate the reading at t - 0.2 by the weighted average 1.0. One way to estimate what the intermediate readings would = (1- ?) U 12) + G) f(25) f(0.2) In general, to estimate the reading at time t, let a be the largest time less than t at which a reading was taken, and b be the smallest time after t at which a reading was taken. (For example, if t = .36, then in the example we would have a = .25 and b = .37.) Then the estimate for the reading at t is given by f(a) + f (b) Write a C++ program that does the following: 1. First, it should prompt the user for the input file name and open that file, exiting with an error message if the file can't be opened 2. Then it should prompt the user for an output file name and open that file for writing, exiting with an error message if the file can't be openedExplanation / Answer
/*Assuming the file contains data like
x f(x)
where x is increasing line by line
*/
#include<iostream>
#include<fstream>
using namespace std;
int main(){
double x[100];
double fx[100];
double xreq;
cout << "Enter the input file name:";
string name;
cin >> name;
ifstream fin(name.c_str());
if (!fin){
cout << "Error opening file ";
return 0;
}
cout << "Enter the output file name:";
string name1;
cin >> name1;
ofstream fout(name1.c_str());
if (!fout){
cout << "Error opening file ";
return 0;
}
int count = 0;
while(fin >> x[count] >> fx[count])
count++;
cout << "Enter x at which f(x) needs to be calculated:";
cin >> xreq;
double xmin;
double xmax;
double fxmin;
double fxmax;
double ans = -1;
for (int i = 0; i<count; i++){
if (x[i] < xreq){
xmin = x[i];
fxmin = fx[i];
}
if (x[i] == xreq){
ans = fx[i];
break;
}
if (x[i] > xreq){
xmax = x[i];
fxmax = fx[i];
break;
}
}
if (ans != -1){
cout << ans << endl;
}
else {
ans = ((xmax - xreq)/(xmax - xmin))*fxmin + ((xreq - xmin)/(xmax-xmin))*fxmax;
cout << ans << endl;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.