Untitled

 avatar
unknown
plain_text
a year ago
2.4 kB
7
Indexable
#include <iostream>
#include <cmath>
#include <cstdio>

using namespace std;

// Q5. Write a function called lookup_table(Xt,Yt,n,x,xl,yl)
// that looks up x from a table of values stored in the
// 1D arrays Xt, Yt (each with n elements), eg

// i    Xt     Yt
// 0    1.0    1.0
// 1    2.1    3.5
// 2    4.5    9.9
// 3    5.5    7.5
// 4    10.0   15.5

// It does this by finding the index value i such that:

// Xt[i] <= x <= Xt[i+1]

// ie x is between consecutive values in the table

// The lookup table values are calculated as follows:

// xl = Xt[i]
// yl = Yt[i]

// If the value of x is out of range (ie the inequality
// can't be satisfied) return 1 otherwise return 0

// assume the values of Xt are in strictly increasing order
// eg

// i    Xt     Yt
// 0    1.0    1.0
// 1    2.1    3.5
// 2    4.5    9.9
// 3    5.5    7.5
// 4    10.0   15.5

// x = 5.1 -> i = 2, xl = 4.5, yl = 9.9

// Q6. Repeat Q1 using "linear interpolation" to calculate
// xl, yl -- ie use the equation of a line between consecutive
// points in the table to get a better estimate using

// xl = x
// yl = Yt[i] + slope * (xl - Xt[i])

// where slope = (Yt[i+1]-Yt[i])/(Xt[i+1]-Xt[i])


int lookup_table(double Xt[], double Yt[], int n,
				 double x, double &xl, double &yl);

// INPUT: Xt[], Yt[], n, x

// OUTPUT: xl, yl

// VALUE: n, x

// REFERENCE: Xt[], Yt[], xl, yl

int main()
{
	// example main to illustrate the function -- not required 
	// for the solution since it wasn't asked for
	
	int n = 5;
    double Xt[5] = {1.0,2.1,4.5,5.5,10.0};
    double Yt[5] = {1.0,3.5,9.9,7.5,15.5};
    double x, xl, yl;
    
    x = 5.1;
    lookup_table(Xt,Yt,n,x,xl,yl);
    
    cout << "\nxl = " << xl;
    cout << "\nyl = " << yl;
   
	cout << "\n\ndone.\n";
	getchar();

	return 0;
}

int lookup_table(double Xt[], double Yt[], int n,
				 double x, double &xl, double &yl)
{
	double slope;
	int i, in_range = 0;
	
	for(i=0;i<(n-1);i++) {
		if( (Xt[i] <= x) && (x <= Xt[i+1]) ) {
			in_range = 1;
			break;
		}
	}
	
	// return 1 if x is out of range
	if( in_range == 0 ) {
		cout << "\nout of range";
		return 1;
	}
	
	// for Q5
	xl = Xt[i];
	yl = Yt[i];
	
	// for Q6
//	xl = x;
//	slope = (Yt[i+1]-Yt[i])/(Xt[i+1]-Xt[i]);
//	yl = Yt[i] + slope * (xl - Xt[i]);

	return 0; // in range
}
Editor is loading...
Leave a Comment