Reputation: 714
I have an array list of values
var v=[0.009865,0.009866,0.009309,0.009831,0.009919,0.009965,0.009806,0.009509,0.009731,0.009888];
I calculate the min,max and difference between the two to make the range
var max=Math.max.apply(this,v)/100;
var min=Math.min.apply(this,v)/100;
var dif=max-min;
console.dir({'max':max,'min':min,'dif':dif});
the console.dir shows
max: 0.00009965
min: 0.00009308999999999999
dif: 0.000006560000000000005
Then I loop through each value attempting to convert them into percentages inside the range
(by finding out how larger the current value is than the min, dividing the answer by the dif and multiplying the result by 100 to get the percent)
for (var i=0;i<v.length;i++){
v[i]=((v[i]-min)/dif)*100;
console.log(v[i]);
}
the console.log shows values I really don't expect to see (expected between 0-100)
148962.04268292672
148977.28658536574
140486.43292682915
148443.74999999985
149785.21341463405
150486.43292682915
148062.65243902427
143535.21341463405
146919.35975609746
149312.65243902427
What am I doing wrong?
My reference to the math: https://math.stackexchange.com/questions/51509/how-to-calculate-percentage-of-value-inside-arbitrary-range
Upvotes: 1
Views: 1207
Reputation: 122916
You could to this using Array.map
, something like:
var v= [0.009865,0.009866,0.009309,0.009831,0.009919,0.009965,
0.009806,0.009509,0.009731,0.009888]
,vv= v.map( function (a) {
return ( ( Math.abs(a-this.min) / this.diff() )*100 )
.toFixed(2);
},
{min: Math.min.apply(null, v),
max: Math.max.apply(null, v),
diff: function () { return this.max-this.min; } }
);
// => returns vv
// ["84.76", "84.91", "0.00", "79.57", "92.99", "100.00",
// "75.76", "30.49", "64.33", "88.26"]
MDN documentation on Array.prototype.map
Upvotes: 0
Reputation: 781096
Don't divide by 100
when setting max
and min
:
var max=Math.max.apply(this,v);
var min=Math.min.apply(this,v);
Output:
84.7560975609757
84.90853658536585
0
79.57317073170726
92.9878048780489
100
75.76219512195132
30.487804878048845
64.32926829268297
88.26219512195112
Upvotes: 5