Reputation: 932
I have a list of int values:
List<int> histogram;
How do I normalize all values so that the max value in the list is always 100?
Upvotes: 11
Views: 27206
Reputation: 1299
To normalize a set of numbers that may contain negative values,
and to define the normalized scale's range:
List<int> list = new List<int>{-5,-4,-3,-2,-1,0,1,2,3,4,5};
double scaleMin = -1; //the normalized minimum desired
double scaleMax = 1; //the normalized maximum desired
double valueMax = list.Max();
double valueMin = list.Min();
double valueRange = valueMax - valueMin;
double scaleRange = scaleMax - scaleMin;
IEnumerable<double> normalized =
list.Select (i =>
((scaleRange * (i - valueMin))
/ valueRange)
+ scaleMin);
Upvotes: 9
Reputation: 44307
If you have a list of strictly positive numbers, then Dav's answer will suit you fine.
If the list can be any numbers at all, then you need to also normalise to a lowerbound.
Assuming an upper bound of 100 and a lower bound of 0, you'll want something like this ...
var max = list.Max();
var min = list.Min();
var range = (double)(max - min);
var normalised
= list.Select( i => 100 * (i - min)/range)
.ToList();
Handling the case where min == max
is left as an exercise for the reader ...
Upvotes: 9
Reputation: 526623
Iterate though, find the maximum value (call it MAXVAL
), then iterate through once more and multiply every value in the list by (100/MAXVAL)
.
var ratio = 100.0 / list.Max();
var normalizedList = list.Select(i => i * ratio).ToList();
Upvotes: 16