开发者

Get value from array using any given t

What I am trying to accomplish, is to be able to put some values inside an array, then based on a t (0-1), get a value out of the array based on its stored values.

To make this more clear, here's an example:

Array values = [0, 10]

Now this array would return value 0 for t=1 and value 10 for t=1. So t=.3 will give a value of 3.

Another example:

Array values = [10, 5, 5, 35]

t=.25 will give a value of 5
t=.125 will give a value of 7.5

Im looking for the most eff开发者_如何学Cicient formula to get the value at any given t using a given array.

Currently I'm using this (pseudo code)

var t:Number = .25;
var values:Array = [10, 5, 5, 35];

if(t == 1) value = [values.length-1];
else
var offset:Number = 1/values.length;
var startIndex:int = int(t/offset);
var fraction:Number = t % offset;
var roundPart:Number = (values[startIndex+1] - values[startIndex]) * fraction;

var value:Number = values[startIndex] + roundPart;

But i'm sure there's a far more better way of doing this. So i'm calling for the mathematicians on here!


Here is a One Liner in Mathematica. It's doing the same thing you are, only slightly more compact.

Arrays indexes start at 1.

values = {10, 5, 5, 35, 0}
f[a_, x_] := a[[k = IntegerPart[(k1 = (Dimensions[a][[1]] - 2) x)] + 1]] + 
             FractionalPart[k1] (a[[k + 1]] - a[[k]])  

So your interpolation result on:

In[198]:= f[values,1]
Out[198]= 35

Etc. If you plot changing the x scale:

Get value from array using any given t

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜