开发者

how to convert any number of list to between 0 and 1

开发者 https://www.devze.com 2023-01-04 06:44 出处:网络
For example : I have the number of list like below : {12,23,34,45,65} to change between 0 and 1 like {0, 0.2, 0.4, 0.6, 0.8}. Does any开发者_如何学运维 body know some algorithm?double max = 1.0 * ol

For example :

I have the number of list like below : {12,23,34,45,65} to change between 0 and 1 like {0, 0.2, 0.4, 0.6, 0.8}. Does any开发者_如何学运维 body know some algorithm?


double max = 1.0 * oldList.Max();
var newList = oldList.Select(x => x / max);

If you want the lowest number to map to 0 then you'll need something like this:

double min = 1.0 * oldList.Min();
double max = 1.0 * oldList.Max();
var newList = oldList.Select(x => (x - min) / (max - min));


A very easy and efficient way to do this is to do a logit transformation. Logit formula is:

y = ln (x / (1 - x))

where y is a number between 0 and 1, following the binary distribution. Also, it is great because y can be zero or negative.

So let's do the way around it, so we can transform our data (y) into binominal distribution (infinite numbers constricted between 0 and 1).

y = ln (x / (1 - x))
exp(y) = exp (ln(x / (1 - x)) # to get rid of ln() we can make the exp() on both sides
exp(y) = x / (1 - x)          # exponential rule: exp(ln(z)) = z

x = exp(y) * (1 - x)
x = exp(y) - x * exp(y)
x + x * exp(y) = exp(y)
x (1 + exp(y) = exp(y)

x = exp(y)/(1 + exp(y))

This is WAY easier and simpler than the other suggestions! I hope that helps!


  1. Find the max number in the sequence.
  2. Divide all the numbers by the max number


Algorithm:

  • find maximum and minimum
  • divide each (element - minimum) by (maximum - minimum)

Note: This will map the maximum to 1.0 ... which however is not the case in your example.

Edit:

var min = list.First();    // assumes a sorted list, else use Min()
var max = list.Last();     // assumes a sorted list, else use Max()
double difference = max - min;
var newList = list.Select( i => Math.Round( (i - min ) / difference, 1 ) );


If you want the lowest to map to 0, and the highest to map to 1, then the following will achieve this:

var input = new double[] { 12, 23, 34, 45, 65 };

var outputList = input.ToList().Select(i => (i - input.Min()) / (input.Max() - input.Min()));

foreach (var i in outputList)
{
    Console.WriteLine(i);
}


expecting you want the highest to be 1.0 and the lowest value to be 0.0 and your array is in order from lowest to highest:

int lowest = myArray[0];
int highest = myArray[myArray.Length-1];
int diff = highest - lowest;

foreach (int item in myArray)
    Console.WriteLine = (float)(item - lowest) / diff;
0

精彩评论

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