Last active
March 24, 2016 22:21
-
-
Save tamamu/129c9f923e2cc79b1a33 to your computer and use it in GitHub Desktop.
最小二乗法 in Rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::io; | |
fn main() { | |
let mut sxi :f64 = 0.0; | |
let mut syi :f64 = 0.0; | |
let mut sxiyi:f64 = 0.0; | |
let mut sxi2 :f64 = 0.0; | |
let mut n :f64 = 0.0; | |
loop { | |
let mut line = String::new(); | |
let size = io::stdin().read_line(&mut line) | |
.ok() | |
.expect("failed to read line"); | |
if size <= 1 { | |
break; | |
} | |
let words :Vec<&str> = line.split_whitespace() | |
.collect(); | |
if words.len() < 2 { | |
println!("Please input two numbers."); | |
continue; | |
} | |
let xi = words[0].parse::<f64>() | |
.expect("value of X is invalid"); | |
let yi = words[1].parse::<f64>() | |
.expect("value of Y is invalid"); | |
sxi += xi; | |
syi += yi; | |
sxiyi += xi*yi; | |
sxi2 += xi*xi; | |
n += 1.0; | |
} | |
if n > 1.0 { | |
let a0 = (sxi2*syi - sxiyi*sxi) / (n*sxi2 - sxi*sxi); | |
let a1 = (n*sxiyi - sxi*syi) / (n*sxi2 - sxi*sxi); | |
println!("{}", a0); | |
println!("{}", a1) | |
}else{ | |
println!("Data is not enough."); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment