1pub struct Neuron {
17 pub threshold: f64,
18}
19
20impl Neuron {
21 pub fn new(threshold: f64) -> Self {
23 Self { threshold }
24 }
25
26 pub fn activate(&self, inputs: &[f64]) -> f64 {
28 let sum: f64 = inputs.iter().sum();
29 if sum >= self.threshold {
30 1.0
31 } else {
32 0.0
33 }
34 }
35}
36
37pub mod utils {
39 pub fn sigmoid(x: f64) -> f64 {
41 1.0 / (1.0 + (-x).exp())
42 }
43
44 pub fn relu(x: f64) -> f64 {
46 x.max(0.0)
47 }
48}
49
50#[cfg(test)]
51mod tests {
52 use super::*;
53
54 #[test]
55 fn neuron_activates_above_threshold() {
56 let neuron = Neuron::new(0.5);
57 let result = neuron.activate(&[0.3, 0.4]);
58 assert_eq!(result, 1.0);
59 }
60
61 #[test]
62 fn neuron_does_not_activate_below_threshold() {
63 let neuron = Neuron::new(0.5);
64 let result = neuron.activate(&[0.1, 0.2]);
65 assert_eq!(result, 0.0);
66 }
67
68 #[test]
69 fn sigmoid_function_works() {
70 let result = utils::sigmoid(0.0);
71 assert!((result - 0.5).abs() < f64::EPSILON);
72 }
73
74 #[test]
75 fn relu_function_works() {
76 assert_eq!(utils::relu(-1.0), 0.0);
77 assert_eq!(utils::relu(1.0), 1.0);
78 }
79}