Jump to content

Calculating the value of e: Difference between revisions

m
→‎{{header|Zig}}: Update Zig code to Zig 0.11.0
m (→‎{{header|Zig}}: Update Zig code to Zig 0.11.0)
Line 4,327:
</pre>
=={{header|Zig}}==
{{works with|Zig|0.11.0}}
This uses the continued fraction method to generate the maximum ratio that can be computed using 64 bit math. The final ratio is correct to 35 decimal places.
<syntaxhighlight lang="zig">
const std = @import("std");
const math = std.math;
const stdout = std.io.getStdOut().writer();
 
pub fn main() !void {
const stdout = std.io.getStdOut().writer();
 
var n: u32 = 0;
var state: u2 = 0;
Line 4,361 ⟶ 4,362:
},
}
varconst p2: u64ov1 = undefined@mulWithOverflow(a, p1);
varif q2: u64(ov1[1] != undefined0) break;
ifconst ov2 = (@mulWithOverflowaddWithOverflow(u64ov1[0], a, p1, &p2p0) or;
if @addWithOverflow(u64, p2,ov2[1] p0,!= &p20) orbreak;
const ov3 = @mulWithOverflow(u64, a, q1, &q2) or;
if @addWithOverflow(u64,ov3[1] q2,!= q0,0) &q2))break;
const ov4 = @addWithOverflow(ov3[0], q0);
{
if (ov4[1] != 0) break;
}const p2 = ov2[0];
const q2 = ov4[0];
try stdout.print("e ~= {d:>19} / {d:>19} = ", .{p2, q2});
 
try dec_print(stdout, p2, q2, 36);
try stdout.print("e ~= {d:>19} / {d:>19} = ", .{ p2, q2 });
try dec_printdecPrint(stdout, p2, q2, 36);
try stdout.writeByte('\n');
p0 = p1;
Line 4,380 ⟶ 4,383:
}
 
fn dec_printdecPrint(ostream: anytype, num: u64, den: u64, prec: usize) !void {
// print out integer part.
try ostream.print("{}.", .{num / den});
Line 4,387 ⟶ 4,390:
// multiply by 10 could potentially overflow a u64.
//
const m: u128 = @intCast(u128, den);
var r = @as(u128, num) % m;
var dec: usize = 0; // decimal place we're in.
Line 4,394 ⟶ 4,397:
r = n % m;
dec += 1;
const ch = @intCastas(u8, @intCast(n / m)) + '0';
try ostream.writeByte(ch);
}
Line 4,443 ⟶ 4,446:
e ~= 5739439214861417731 / 2111421691000680031 = 2.718281828459045235360287471352662497
</pre>
 
=={{header|zkl}}==
{{trans|C}}
59

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.