Calculate Median in C#

Calculate median in c#

Is there a function in the .net Math library?

No.

It's not hard to write your own though. The naive algorithm sorts the array and picks the middle (or the average of the two middle) elements. However, this algorithm is O(n log n) while its possible to solve this problem in O(n) time. You want to look at selection algorithms to get such an algorithm.

How the get the mean, median and stdev from list

This will get you started by showing how to calculate the Average. Note the use of First or Last to get the first / last entry from each of the sub-lists.

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApp5
{
class Program
{
static void Main(string[] args)
{
var myList = new List<List<double>>();

myList.Add(new List<double> { 1, 3, 6, 8 });
myList.Add(new List<double> { 1, 2, 3, 4 });
myList.Add(new List<double> { 1, 4, 8, 12 });

var averageFirst= myList.Select(z => z.First()).Average();
var averageLast = myList.Select(z => z.Last()).Average();

Console.WriteLine(averageFirst);
Console.WriteLine(averageLast);

Console.ReadLine();
}
}
}

Add a Median Method to a List

Use an extension method, and make a copy of the inputted array/list.

public static decimal GetMedian(this IEnumerable<int> source)
{
// Create a copy of the input, and sort the copy
int[] temp = source.ToArray();
Array.Sort(temp);

int count = temp.Length;
if (count == 0)
{
throw new InvalidOperationException("Empty collection");
}
else if (count % 2 == 0)
{
// count is even, average two middle elements
int a = temp[count / 2 - 1];
int b = temp[count / 2];
return (a + b) / 2m;
}
else
{
// count is odd, return the middle element
return temp[count / 2];
}
}

Calculating Median Absolute Deviation in C#

Median is a middle element of the sorted array (or average of two middle items if the array has even items):

  double[] source = new double[] { 1, 2, 3, 4, 5 };

Array.Sort(source);

double med = source.Length % 2 == 0
? (source[source.Length / 2 - 1] + source[source.Length / 2]) / 2.0
: source[source.Length / 2];

double[] d = source
.Select(x => Math.Abs(x - med))
.OrderBy(x => x)
.ToArray();

double MADe = 1.483 * (d.Length % 2 == 0
? (d[d.Length / 2 - 1] + d[d.Length / 2]) / 2.0
: d[d.Length / 2]);

Find median value of 3 user inputted numbers in C# Without output: Numbers entered: x, y, z Minimum Value: a Median Value: b

You're code won't compile how it's written right now, but I can see what you're trying to do. You could change it up so it would compile, but it's not the a particularly efficient way of solving it.

Right now, I think you're attempting to write code to check each scenario of the potential order of numbers. You can do it for 3 numbers relatively easy, but what if you want to extend your code to check a list of 10 or 100 numbers?

I think you should add user input to a list, sort the list, then just return the middle value of the list. It's less code and more reliable.

public class FindMedian
{
public List<int> numbersList = new List<int>(); // list to store user input

// constructor
public FindMedian(int n)
{
Console.WriteLine("Please Enter " + n + " numbers. \n\n");

for (int i = 1; i < n + 1; i++)
{
Console.WriteLine("Number " + i + " : ");

numbersList.Add(GetUserInput()); // call's GetUserInput
}

PrintData();
}

// returns int from Console. Will continue to run until a valid int is entered
private int GetUserInput()
{
int temp = 0;
bool numberValid = false;

while (!numberValid)
{
try
{
temp = int.Parse(Console.ReadLine());
numberValid = true;
}

catch
{
Console.WriteLine("Invalid entry. Please try again.\n");
numberValid = false;
}
}

return temp;
}

// prints data after user enteres the correct number of ints
private void PrintData()
{
// If list contains no data
if (numbersList.Count < 3)
{
Console.WriteLine("No User Data Entered");
return;
}

numbersList.Sort(); // Sorts list from smallest to largest

int minimum = numbersList[0];
int median;

// if list count is even and median is average of two middle numbers
if (numbersList.Count % 2 == 0)
{
median = (numbersList[(numbersList.Count / 2) - 2] + numbersList[(numbersList.Count / 2) - 1] / 2);
}

// if list count is odd and median is just middle number
else
{
median = numbersList[(numbersList.Count / 2)];
}

Console.WriteLine("Minimum Number : " + minimum);
Console.WriteLine("Median Number : " + median);
}
}

Code to find median producing incorrect result in C# and over complex code

@someone is correct it is simple as it gets. I believe the correct formula to put inside your PrintData() function is:

if (numbersList.Count % 2 == 0)
{
median = (numbersList[(numbersList.Count / 2) - 1] +
numbersList[(numbersList.Count / 2)]) / 2;
}

The explanation is that in the case of an even numberList Count the / 2 operator gives you the second middle value in the list...
hope this help.

median c# wrong calculate

Your problem is that you are calculating with characters instead of number.

So let's say your textBox1.Text is "1,2,3". Then x1[(n/2)-1] would point at the character '1', which has the double value of 48 or something.

You need to parse the strings into int using int.Parse:

int[] tab = x1.Split(',').Select(s => int.Parse(s)).ToArray();

And then use these values instead the string again:

if (n % 2 == 0)
{
double c = tab[(n / 2) -1]; // tab instead of x1!
double v = tab[(n / 2)]; // tab instead of x1!
wynik = (c + v) / 2;
}
else
wynik = tab[n / 2]; // tab instead of x1


Related Topics



Leave a reply



Submit