0

I'm trying to create a function that return an intersect point between two lines. Below is my code.

fn main() {
    let line_1: (f64, f64) = (-2.0, 9.5);
    let line_2: (f64, f64) = (1.0, -2.0);

    let x_1: f64 = (line_2.1 - line_1.1) / (line_1.0 - line_2.0);
    let y_1: f64 = line_1.0.mul_add(x_1, line_1.1);

    let x_2: f64 = (line_1.1 - line_2.1) / (line_2.0 - line_1.0);
    let y_2: f64 = line_2.0.mul_add(x_2, line_2.1);

    println!("x_1: {}, y_1: {}", x_1, y_1);
    println!("x_2: {}, y_2: {}", x_2, y_2);
}

Mathematically x_1 will be equal with x_2 and y_1 will be equal with y_2. Instead, this is the value that's printed.

x_1: 3.8333333333333335, y_1: 1.833333333333333
x_2: 3.8333333333333335, y_2: 1.8333333333333335

The value isn't supposed to have five in it, and y_1 value is different than y_2. Is this some sort of bug, or there's some steps that I miss on handling floating data?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Matias Alvin
  • 132
  • 7
  • 2
    This has nothing to do with Rust and is an artifact of how floating point numbers work. [What Every Programmer Should Know About Floating-Point Arithmetic](http://floating-point-gui.de/). – Shepmaster Apr 27 '18 at 20:21
  • Ah I see, guess I forgot the basic. Thank you – Matias Alvin Apr 27 '18 at 20:28

0 Answers0