linear_regression/
lib.rs

1/*
2<----------------------------------
3Author: Ilia Sichinava 
4Date: December 3rd, 2022
5Title: Linear Regression
6---------------------------------->
7*/
8use core::panic;
9
10// Define struct for unknown k and b values
11pub struct Equation {
12    k: f32,
13    b: f32
14}
15
16
17// Returns k and b, prints equation
18pub fn linear_regression(data: &Vec<(f32, f32)>) -> Equation {
19    // Check for empty data
20    if data.len() == 0 {
21        panic!("Enter non-zero data")
22    }
23
24    // Find everything for our k and b
25    let x_mean: f32 = data.iter().map(|point| point.1).sum::<f32>() / data.len() as f32;
26    let y_mean: f32 = data.iter().map(|point| point.0).sum::<f32>() / data.len() as f32;
27    let xy_mean: f32 = data.iter().map(|point| point.1 * point.0).sum::<f32>() / data.len() as f32;
28    let x_square_mean: f32 = data.iter().map(|point| point.1 * point.1).sum::<f32>() / data.len() as f32;
29
30    // ------------------------->
31    if x_square_mean - (x_mean * x_mean) == 0.0 {
32        panic!("Can't divide by zero")
33    }
34
35    // Now let's calculate them
36    let k: f32 = (xy_mean - (x_mean * y_mean)) / (x_square_mean - (x_mean * x_mean));
37    let b: f32 = y_mean - (k * x_mean);
38    
39    print!("Regression line: ");
40    #[allow(illegal_floating_point_literal_pattern)]
41    // Check for k and b to display data correctly. 
42    // Print y = x + 3 instead of y = 1x + 3
43    match (k, b) {
44        // Cases where k = 1
45        (1.0, 0.0) => println!("y = x"),
46        (1.0, _) => println!("y = x + {}", b),        
47        (0.0, _) => println!("y = {}", b),
48
49        // Case where b = 0
50        (_, 0.0) => println!("y = {}x", k),
51        
52        // k != 1 && b != 0
53        _ => println!("y = {}x + {}", k, b)
54    }
55    println!("-----------------------------------------");
56    
57    // Return found equation members and use them for predictions afterwards
58    Equation { k, b }
59}
60
61pub fn predict(e: &Equation, x: f32) -> () {
62    // Simply count y from y = kx + b equation
63    println!("In {} Georgian GDP would be: ${:.3}B\nBut now it is $18.7B", x, e.k * x + e.b);
64}