2 // interpolater.cxx -- routines to handle linear interpolation from a table of
3 // x,y The table must be sorted by "x" in ascending order
5 // Written by Curtis Olson, started April 1998.
7 // Copyright (C) 1998 Curtis L. Olson - curt@me.umn.edu
9 // This library is free software; you can redistribute it and/or
10 // modify it under the terms of the GNU Library General Public
11 // License as published by the Free Software Foundation; either
12 // version 2 of the License, or (at your option) any later version.
14 // This library is distributed in the hope that it will be useful,
15 // but WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 // Library General Public License for more details.
19 // You should have received a copy of the GNU Library General Public
20 // License along with this library; if not, write to the
21 // Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22 // Boston, MA 02111-1307, USA.
27 #include <simgear/compiler.h>
29 #include <stdlib.h> // for exit()
33 #include <simgear/fg_zlib.h>
34 #include <simgear/debug/logstream.hxx>
35 #include <simgear/misc/fgstream.hxx>
37 #include "interpolater.hxx"
42 // Constructor -- loads the interpolation table from the specified
44 SGInterpTable::SGInterpTable( const string& file ) {
45 SG_LOG( SG_MATH, SG_INFO, "Initializing Interpolator for " << file );
47 fg_gzifstream in( file );
48 if ( !in.is_open() ) {
49 SG_LOG( SG_GENERAL, SG_ALERT, "Cannot open file: " << file );
56 if ( size < MAX_TABLE_SIZE ) {
57 in >> table[size][0] >> table[size][1];
61 SG_LOG( SG_MATH, SG_ALERT,
62 "fgInterpolateInit(): Exceed max table size = "
70 // Given an x value, linearly interpolate the y value from the table
71 double SGInterpTable::interpolate(double x) {
77 while ( (x > table[i][0]) && (i < size) ) {
78 // cout << " i = " << i << " table[i][0] = " << table[i][0] << endl;
79 // cout << " size = " << size << endl;
83 // printf ("i = %d ", i);
85 if ( (i == 0) && (x < table[0][0]) ) {
86 SG_LOG( SG_MATH, SG_DEBUG,
87 "interpolate(): lookup error, x to small = " << x );
91 // cout << " table[size-1][0] = " << table[size-1][0] << endl;
92 if ( x > table[size-1][0] ) {
93 SG_LOG( SG_MATH, SG_DEBUG,
94 "interpolate(): lookup error, x to big = " << x );
95 return table[size-1][1];
98 // y = y1 + (y0 - y1)(x - x1) / (x0 - x1)
100 ( (table[i-1][1] - table[i][1]) *
101 (x - table[i][0]) ) /
102 (table[i-1][0] - table[i][0]);
109 SGInterpTable::~SGInterpTable( void ) {