Java Reference

In-Depth Information

Listing 5-7.
PolynomialInterpolator.fx

public class PolynomialInterpolator extends SimpleInterpolator{

public var solveFor = 0 on replace{

solve();

}

public var coefficients:Number[] = [1.0, 1.0, 1.0] on replace{

solve();

}

init{

solve();

}

public function solve():Void{

//given a + b + c = 1, then c = 1 - b - c, or a = 1 - c - b

if (solveFor != -1){

var solvedValue = 1.0;

for (index in [0..(sizeof coefficients)-1]){

if (index != solveFor){

solvedValue -= coefficients[index];

}

}

coefficients[solveFor] = solvedValue;

}

}

public override function curve(fraction:Number):Number{

var power = fraction;

var total = 0.0;

for (coeff in coefficients){

total += coeff*power;

power *= fraction;

}

return total;

}

}

Instead of specifying a, b, c, and so on, the implementation above uses a
Sequence
called

coefficients
to store an arbitrary number of terms. It should be pointed out that
coefficients
stores in

the sequence in the reverse order of the function in Listing 5-7. So,
coefficients[0]
is the least

significant term.

The variable
solveFor
is used to keep track of which coefficient must be solved for when one of the

others changes. This is an improvement over the previous versions, where the least significant

coefficient was always solved for.

The function
solve
is called every time the
Sequence
coefficients
changes and once during init

time. The function
solve
calculates a value for one of the coefficients to make sure the function always

creates a curve that passes through the origin and the point 1,1.