Skip to content

Instantly share code, notes, and snippets.

@cookie-s
Created November 25, 2017 01:00
Show Gist options
  • Save cookie-s/287750742c55fd7bc6ffc8614b1d71fb to your computer and use it in GitHub Desktop.
Save cookie-s/287750742c55fd7bc6ffc8614b1d71fb to your computer and use it in GitHub Desktop.
#![feature(rustc_private)]
extern crate rand;
use rand::Rng;
use std::ops::{Add, Sub};
#[derive(Clone, Copy, Debug)]
struct Pt {
x : f64,
y : f64,
}
impl Pt {
fn new(x : f64, y : f64) -> Self {
Pt{x:x, y:y}
}
fn rand(rng : &mut rand::ThreadRng) -> Self {
Self::new(rng.gen(), rng.gen())
}
fn dot(&self, other : &Self) -> f64 {
self.x * other.x + self.y * other.y
}
fn normsq(&self) -> f64 {
self.dot(self)
}
}
impl Add for Pt {
type Output = Self;
fn add(self, other : Self) -> Self {
Self::new(self.x + other.x, self.y + other.y)
}
}
impl Sub for Pt {
type Output = Self;
fn sub(self, other : Self) -> Self {
Self::new(self.x - other.x, self.y - other.y)
}
}
fn tri_surface(a : Pt, b : Pt, c : Pt) -> f64 {
let v1 = c-a;
let v2 = b-a;
(v1.normsq() * v2.normsq() - v1.dot(&v2) * v1.dot(&v2)).sqrt() / 2.0
}
fn main() {
let mut rng = rand::thread_rng();
let mut sum = 0.0;
let tries = 1000000;
for _ in 1..tries {
let (a, b, c) = (Pt::rand(&mut rng), Pt::rand(&mut rng), Pt::rand(&mut rng));
sum += tri_surface(a, b, c);
}
println!("{}", sum / tries as f64);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment