0

So, with C# I am working with a dataset that contains a variable which can have a value of various ranges that I am unable to predetermine. The range is a value that can range from -x to x, with the median at 0, and x could be a range such as -15 to 15, or it could be -1 to 1. The data I receive is more based on the deviation from 0 than from the range min to the range max, and I believe this is vital to the formula.

I am trying to convert the range of -x to x, to be either in the range of 0 to 100, or -1 to 1, all while maintaining the original ratios. I have taken a look at Convert a number range to another range, maintaining ratio but the formulas there require a known and predetermined range min and max to start with. Math is certainly not my strong suit and I am at a total loss of how to convert this data, so any help here would be greatly appreciated.

If it does help any, the data I receive is in a list/array, something like:

x[]:{ 1.47f, 1.21f, 0.49f, -0.05f, -0.69f, -1.8f, -2.35f, -1.2f, -0.42f, 4.56f }

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
  • My ultimate goal with this is to graph the data onto a UI line graph of size x:200, y:100, with the 0 value being centered on the y-axis, and the graph being plotted over time across the x-axis. So, the minimum value should be the lowest value on the graph, being 0 on the y-axis, and the maximum value should be 100 on the y-axis, with the middle values being plotted between these values while maintaining the ratio between them. – Cody Nason Feb 14 '22 at 05:28

1 Answers1

1

So you effectively want to turn your values into a percentage, where you maximum and minimum values are defined within your data, and hence not known in advance.

Knowing this then you can use the maths provided in this solution: Maths Range To Percentage

Then the following code should work.

float[] range = { 1.47f, 1.21f, 0.49f, -0.05f, -0.69f, -1.8f, -2.35f, -1.2f, -0.42f, 4.56f };
float min = range.Min();
float max = range.Max();

float[] newValue = new float[range.Length];
for (int i = 0; i < range.Length; i++)
    newValue[i] = (range[i] - min) / (max - min);

for (int i = 0; i < range.Length; i++)            
    Console.WriteLine($"Value: {range[i]}:  New Value {newValue[i]}");

This produces a value between 0 and 1, if you want to convert to to a value between 0 and 100, then you just need to multiply it by 100.

jason.kaisersmith
  • 8,712
  • 3
  • 29
  • 51