Skip to content
Snippets Groups Projects
Commit 1429b6f2 authored by Thomas Kennedy's avatar Thomas Kennedy
Browse files

Clean up argument parsing

parent 6e6036b4
No related branches found
No related tags found
No related merge requests found
......@@ -13,7 +13,6 @@ struct Point(f64, f64);
///
/// Yields:
/// A sequence of points in the form (x, f(x))
fn generate_random_points(
f: fn(f64) -> f64,
lower_limit: f64,
......@@ -31,20 +30,47 @@ fn generate_random_points(
.collect()
}
/// Handle positional command line argument validation.
///
/// # Return
/// Tuple in the form (lower limit, upper limit, maximum magnitude)
fn parse_cmd_args() -> (f64, f64, u32) {
let args: Vec<String> = env::args().collect();
if args.len() < 4 {
eprintln!(
"Usage:\n {} not_used num_points a b max_magnitude",
args[0]
);
std::process::exit(1);
}
let limit_a = args[2]
.parse::<f64>()
.unwrap_or_else(|_err| std::process::exit(2));
let limit_b = args[3]
.parse::<f64>()
.unwrap_or_else(|_err| std::process::exit(3));
let max_magnitude = args[4]
.parse::<u32>()
.unwrap_or_else(|_err| std::process::exit(4));
(limit_a, limit_b, max_magnitude)
}
/// This main demonstrates the impact of the number of points on Monte Carlo
/// integration
fn main() {
let num_points = env::args().nth(1).unwrap().parse::<u64>(); // Unused in this version of main
let limit_a = env::args().nth(2).unwrap().parse::<f64>().unwrap();
let limit_b = env::args().nth(3).unwrap().parse::<f64>().unwrap();
let max_magnitude = env::args().nth(4).unwrap().parse::<u32>().unwrap();
let (limit_a, limit_b, max_magnitude) = parse_cmd_args();
let math_f = |x: f64| x.powf(2_f64);
println!("| {:^16} | {:^20} |", "# Points", "Est. f(x)");
let max_num_points: u64 = 2_u64.pow(max_magnitude);
let point_sequence = (generate_random_points(math_f, limit_a, limit_b, max_num_points));
let point_sequence = generate_random_points(math_f, limit_a, limit_b, max_num_points);
for magnitude in 0..=max_magnitude {
let num_points = 2_u64.pow(magnitude);
......@@ -52,7 +78,7 @@ fn main() {
let sum_of_f_of_x_values: f64 = point_sequence
.iter()
.map(|point| point.1)
.take((num_points as usize))
.take(num_points as usize)
.sum();
let integral_result = (limit_b - limit_a) / (num_points as f64) * sum_of_f_of_x_values;
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment