fork download
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Drawing;
  5.  
  6. public class Program
  7. {
  8. /// <summary>
  9. /// Gets the value at a given X using the line of best fit (Least Square Method) to determine the equation
  10. /// </summary>
  11. /// <param name="points">Points to calculate the value from</param>
  12. /// <param name="x">Function input</param>
  13. /// <returns>Value at X in the given points</returns>
  14. public static float LeastSquaresValueAtX(List<PointF> points, float x)
  15. {
  16. float slope = SlopeOfPoints(points);
  17. float yIntercept = YInterceptOfPoints(points, slope);
  18.  
  19. return (slope * x) + yIntercept;
  20. }
  21.  
  22. /// <summary>
  23. /// Gets the slope for a set of points using the formula:
  24. /// m = ? (x-AVG(x)(y-AVG(y)) / ? (x-AVG(x))²
  25. /// </summary>
  26. /// <param name="points">Points to calculate the Slope from</param>
  27. /// <returns>SlopeOfPoints</returns>
  28. private static float SlopeOfPoints(List<PointF> points)
  29. {
  30. float xBar = points.Average(p => p.X);
  31. float yBar = points.Average(p => p.Y);
  32.  
  33. float dividend = points.Sum(p => (p.X - xBar) * (p.Y - yBar));
  34. float divisor = (float)points.Sum(p => Math.Pow(p.X - xBar, 2));
  35.  
  36. return dividend / divisor;
  37. }
  38.  
  39. /// <summary>
  40. /// Gets the Y-Intercept for a set of points using the formula:
  41. /// b = AVG(y) - m( AVG(x) )
  42. /// </summary>
  43. /// <param name="points">Points to calculate the intercept from</param>
  44. /// <returns>Y-Intercept</returns>
  45. private static float YInterceptOfPoints(List<PointF> points, float slope)
  46. {
  47. float xBar = points.Average(p => p.X);
  48. float yBar = points.Average(p => p.Y);
  49.  
  50. return yBar - (slope * xBar);
  51. }
  52. public static void Main()
  53. {
  54. Console.WriteLine("Hello C#");
  55. }
  56. }
  57.  
Success #stdin #stdout 0s 29672KB
stdin
Standard input is empty
stdout
Hello C#