Sum of a series: Difference between revisions

Content added Content deleted
(→‎{{header|RPL}}: HP-49+ version)
m (→‎Zig: Change sum to u64 (from i64). Update Zig code to Zig 0.11.0)
Line 3,379: Line 3,379:


=={{header|Zig}}==
=={{header|Zig}}==
{{Works with|Zig|0.11.0}}
<syntaxhighlight lang="zig">const std = @import("std");
<syntaxhighlight lang="zig">const std = @import("std");


fn f(x: i64) f64 {
fn f(x: u64) f64 {
return 1/@intToFloat(f64, x*x);
return 1 / @as(f64, @floatFromInt(x * x));
}
}


fn S(fun: fn(i64) f64, n: i64) f64 {
fn sum(comptime func: fn (u64) f64, n: u64) f64 {
var s: f64 = 0.0;
var s: f64 = 0.0;
var i: i64 = n;
var i: u64 = n;

while (i != 0) : (i -= 1)
s += func(i);


while (i > 0) : (i -= 1) {
s += fun(i);
}
return s;
return s;
}
}


pub fn main() !void
pub fn main() !void {
{
const stdout = std.io.getStdOut().writer();
const stdout = std.io.getStdOut().writer();
try stdout.print("S_1000 = {d:.15}\n", .{S(f, 1000)});
try stdout.print("S_1000 = {d:.15}\n", .{sum(f, 1000)});
}</syntaxhighlight>
}</syntaxhighlight>{{out}}
{{out}}
<pre>S_1000 = 1.643934566681560</pre>
<pre>S_1000 = 1.643934566681560</pre>