Scale Data to New Range
TODO: collapasable, copyable, download, etc
How do I scale one range of numbers over to a different target range? Example
var data = [100, 103, 107, 90, 95, 102];
var min = 90; var max = 107;
var diff = 17;
targetMin = -3; targetMax = 3; To scale a range of numbers to a different target range, you can use a simple formula that maps the original range to the target range. This process involves finding the ratio of the difference between a number in the original range and the original minimum to the total span of the original range, and then applying this ratio to the span of the target range. Finally, you adjust by adding the target minimum to re-base the scaled value within the target range.
Given your example, you want to map the range ([90, 107]) to ([-3, 3]). Here's how you can do it:
- Calculate the span of the original range (you've already done this with
diff = 17
). - Calculate the span of the target range (
targetMax - targetMin
). - For each number in the original data, apply the following formula to scale:
[ \text{scaledValue} = \left( \frac{\text{originalValue} - \text{min}}{\text{diff}} \right) \times (\text{targetMax} - \text{targetMin}) + \text{targetMin} ]
Where:
originalValue
is the current number from the data array you're scaling.min
is the minimum value of the original range.diff
is the difference between the max and min of the original range.targetMin
andtargetMax
are the bounds of the target range.
Here's how you can implement it in JavaScript:
var data = [100, 103, 107, 90, 95, 102];
var min = 90;
var max = 107;
var diff = max - min; // This is 17 as you've calculated
var targetMin = -3;
var targetMax = 3;
// Function to scale a single value
function scaleValue(value, min, max, targetMin, targetMax) {
return ((value - min) / (max - min)) * (targetMax - targetMin) + targetMin;
}
// Scale the entire dataset
var scaledData = data.map(function(value) {
return scaleValue(value, min, max, targetMin, targetMax);
});
console.log(scaledData);
This script first defines a function scaleValue
that applies the scaling formula to a single value. It then uses the .map()
function to apply this scaling to each value in the data
array, producing a new array scaledData
with the scaled values.
This approach allows you to easily adjust the original and target ranges as needed without having to rewrite the logic each time.
Scale Data to New Range created at Tue Jan 20 1970 18:23:24 GMT+0000 (Coordinated Universal Time)Related Chats
Aggregate Highcharts data in 5-min. 0.398
Sort Array with JS 0.340
Arrays de Arrays Swift. 0.336
Modify Cylinder Properties 0.324
Smoothly Animate Value with Timestamp 0.324
Draw California and Florida. 0.319
Move Entity Up 0.005 0.312
Convert Objects to Set 0.305
Highlighting Graph Area 0.288