Fix count to actually _be_ a count

Also, start from 1 in the positive direction, instead of 5, since that
is more how the thing works (sorry, mathematician brain).

Additionally, adds some extra information in the comments:
information about how long the code would take if one actually sets
count to 2,5 * 10^12, and adding a plus in front of the 4/1 to show that
that is in fact the first element of the "plus" side.

Finally, add an (floating point) error to the debug print.
This commit is contained in:
Nicole Patricia Mazzuca
2026-06-01 22:25:08 +02:00
parent 83a89702b2
commit a03b676bed
3 changed files with 19 additions and 18 deletions
+14 -12
View File
@@ -28,9 +28,9 @@
// We will not go into the formula and its derivation in detail, but
// will deal with the series straight away:
//
// 4 4 4 4 4
// PI = --- - --- + --- - --- + --- ...
// 1 3 5 7 9
// 4 4 4 4 4
// PI = + --- - --- + --- - --- + --- ...
// 1 3 5 7 9
//
// As you can clearly see, the series starts with the whole number 4 and
// approaches the circle number by subtracting and adding smaller and
@@ -71,27 +71,28 @@
const std = @import("std");
pub fn main() !void {
const count = 1_000_000_000;
const count = 500_000_000;
var pi_plus: f64 = 0;
var pi_minus: f64 = 0;
{
// First thread to calculate the plus numbers.
const handle1 = try std.Thread.spawn(.{}, thread_pi, .{ &pi_plus, 5, count });
const handle1 = try std.Thread.spawn(.{}, thread_pi, .{ &pi_plus, 1, count });
defer handle1.join();
// Second thread to calculate the minus numbers.
???
}
// Here we add up the results.
std.debug.print("PI ≈ {d:.8}\n", .{4 + pi_plus - pi_minus});
std.debug.print("PI ≈ {d:.8} (error = {e:.1})\n", .{ pi_plus - pi_minus, std.math.pi - (pi_plus - pi_minus) });
}
fn thread_pi(pi: *f64, begin: u64, end: u64) !void {
var n: u64 = begin;
while (n < end) : (n += 4) {
pi.* += 4 / @as(f64, @floatFromInt(n));
fn thread_pi(pi: *f64, begin: u64, count: u64) !void {
for (0..count) |i| {
const term = 4 / @as(f64, @floatFromInt(begin + 4 * i));
pi.* += term;
}
}
// If you wish, you can increase the number of loop passes, which
@@ -106,5 +107,6 @@ fn thread_pi(pi: *f64, begin: u64, end: u64) !void {
// And you should remove the formatting restriction in "print",
// otherwise you will not be able to see the additional digits.
//
// If count = 10_000_000_000_000 you should see the following:
// If count = 2_500_000_000_000, you should see the following:
// 3.141592653589
// (after waiting on the order of 1000 seconds, or 17 minutes)