task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/Averages/Root_mean_square | Averages/Root mean square | Task[edit]
Compute the Root mean square of the numbers 1..10.
The root mean square is also known by its initials RMS (or rms), and as the quadratic mean.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
x
r
m
s
=
x
1
2
+
x
2
2
+
⋯
+
x
n
2
n
.
{\displaystyle x_{\mathrm {rms} }={\sqrt {{{x_{1}}^{2}+{x_{2}}^{2}+\cdots +{x_{n}}^{2}} \over n}}.}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #S-lang | S-lang | define rms(arr)
{
return sqrt(sum(sqr(arr)) / length(arr));
}
print(rms([1:10])); |
http://rosettacode.org/wiki/Averages/Root_mean_square | Averages/Root mean square | Task[edit]
Compute the Root mean square of the numbers 1..10.
The root mean square is also known by its initials RMS (or rms), and as the quadratic mean.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
x
r
m
s
=
x
1
2
+
x
2
2
+
⋯
+
x
n
2
n
.
{\displaystyle x_{\mathrm {rms} }={\sqrt {{{x_{1}}^{2}+{x_{2}}^{2}+\cdots +{x_{n}}^{2}} \over n}}.}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Sather | Sather | class MAIN is
-- irrms stands for Integer Ranged RMS
irrms(i, f:INT):FLT
pre i <= f
is
sum ::= 0;
loop
sum := sum + i.upto!(f).pow(2);
end;
return (sum.flt / (f-i+1).flt).sqrt;
end;
main is
#OUT + irrms(1, 10) + "\n";
end;
end; |
http://rosettacode.org/wiki/Babbage_problem | Babbage problem |
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
What is the smallest positive integer whose square ends in the digits 269,696?
— Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.
He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.
Task[edit]
The task is to find out if Babbage had the right answer — and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand.
As Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.
For these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].
Motivation
The aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.
| #D | D | // It's basically the same as any other version.
// What can be observed is that 269696 is even, so we have to consider only even numbers,
// because only the square of even numbers is even.
import std.math;
import std.stdio;
void main( )
{
// get smallest number <= sqrt(269696)
int k = cast(int)(sqrt(269696.0));
// if root is odd -> make it even
if (k % 2 == 1)
k = k - 1;
// cycle through numbers
while ((k * k) % 1000000 != 269696)
k = k + 2;
// display output
writefln("%d * %d = %d", k, k, k*k);
} |
http://rosettacode.org/wiki/Averages/Simple_moving_average | Averages/Simple moving average | Computing the simple moving average of a series of numbers.
Task[edit]
Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far.
Description
A simple moving average is a method for computing an average of a stream of numbers by only averaging the last P numbers from the stream, where P is known as the period.
It can be implemented by calling an initialing routine with P as its argument, I(P), which should then return a routine that when called with individual, successive members of a stream of numbers, computes the mean of (up to), the last P of them, lets call this SMA().
The word stateful in the task description refers to the need for SMA() to remember certain information between calls to it:
The period, P
An ordered container of at least the last P numbers from each of its individual calls.
Stateful also means that successive calls to I(), the initializer, should return separate routines that do not share saved state so they could be used on two independent streams of data.
Pseudo-code for an implementation of SMA is:
function SMA(number: N):
stateful integer: P
stateful list: stream
number: average
stream.append_last(N)
if stream.length() > P:
# Only average the last P elements of the stream
stream.delete_first()
if stream.length() == 0:
average = 0
else:
average = sum( stream.values() ) / stream.length()
return average
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Type FuncType As Function(As Double) As Double
' These 'shared' variables are available to all functions defined below
Dim Shared p As UInteger
Dim Shared list() As Double
Function sma(n As Double) As Double
Redim Preserve list(0 To UBound(list) + 1)
list(UBound(list)) = n
Dim start As Integer = 0
Dim length As Integer = UBound(list) + 1
If length > p Then
start = UBound(list) - p + 1
length = p
End If
Dim sum As Double = 0.0
For i As Integer = start To UBound(list)
sum += list(i)
Next
Return sum / length
End Function
Function initSma(period As Uinteger) As FuncType
p = period
Erase list '' ensure the array is empty on each initialization
Return @sma
End Function
Dim As FuncType ma = initSma(3)
Print "Period = "; p
Print
For i As Integer = 0 To 9
Print "Add"; i; " => moving average ="; ma(i)
Next
Print
ma = initSma(5)
Print "Period = "; p
Print
For i As Integer = 9 To 0 Step -1
Print "Add"; i; " => moving average ="; ma(i)
Next
Print
Print "Press any key to quit"
Sleep |
http://rosettacode.org/wiki/Barnsley_fern | Barnsley fern |
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS).
Task
Create this fractal fern, using the following transformations:
ƒ1 (chosen 1% of the time)
xn + 1 = 0
yn + 1 = 0.16 yn
ƒ2 (chosen 85% of the time)
xn + 1 = 0.85 xn + 0.04 yn
yn + 1 = −0.04 xn + 0.85 yn + 1.6
ƒ3 (chosen 7% of the time)
xn + 1 = 0.2 xn − 0.26 yn
yn + 1 = 0.23 xn + 0.22 yn + 1.6
ƒ4 (chosen 7% of the time)
xn + 1 = −0.15 xn + 0.28 yn
yn + 1 = 0.26 xn + 0.24 yn + 0.44.
Starting position: x = 0, y = 0
| #Raku | Raku | use Image::PNG::Portable;
my ($w, $h) = (640, 640);
my $png = Image::PNG::Portable.new: :width($w), :height($h);
my ($x, $y) = (0, 0);
for ^2e5 {
my $r = 100.rand;
($x, $y) = do given $r {
when $r <= 1 { ( 0, 0.16 * $y ) }
when $r <= 8 { ( 0.20 * $x - 0.26 * $y, 0.23 * $x + 0.22 * $y + 1.60) }
when $r <= 15 { (-0.15 * $x + 0.28 * $y, 0.26 * $x + 0.24 * $y + 0.44) }
default { ( 0.85 * $x + 0.04 * $y, -0.04 * $x + 0.85 * $y + 1.60) }
};
$png.set(($w / 2 + $x * 60).Int, ($h - $y * 60).Int, 0, 255, 0);
}
$png.write: 'Barnsley-fern-perl6.png'; |
http://rosettacode.org/wiki/Averages/Root_mean_square | Averages/Root mean square | Task[edit]
Compute the Root mean square of the numbers 1..10.
The root mean square is also known by its initials RMS (or rms), and as the quadratic mean.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
x
r
m
s
=
x
1
2
+
x
2
2
+
⋯
+
x
n
2
n
.
{\displaystyle x_{\mathrm {rms} }={\sqrt {{{x_{1}}^{2}+{x_{2}}^{2}+\cdots +{x_{n}}^{2}} \over n}}.}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #S-BASIC | S-BASIC |
var n, sqsum, sqmean, rms = real
sqsum = 0
for n = 1 to 10 do
sqsum = sqsum + (n * n)
next n
sqmean = sqsum / n
rms = sqr(sqmean)
print "RMS of numbers from 1 to 10 = ";rms
end
|
http://rosettacode.org/wiki/Averages/Root_mean_square | Averages/Root mean square | Task[edit]
Compute the Root mean square of the numbers 1..10.
The root mean square is also known by its initials RMS (or rms), and as the quadratic mean.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
x
r
m
s
=
x
1
2
+
x
2
2
+
⋯
+
x
n
2
n
.
{\displaystyle x_{\mathrm {rms} }={\sqrt {{{x_{1}}^{2}+{x_{2}}^{2}+\cdots +{x_{n}}^{2}} \over n}}.}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Scala | Scala | def rms(nums: Seq[Int]) = math.sqrt(nums.map(math.pow(_, 2)).sum / nums.size)
println(rms(1 to 10)) |
http://rosettacode.org/wiki/Babbage_problem | Babbage problem |
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
What is the smallest positive integer whose square ends in the digits 269,696?
— Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.
He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.
Task[edit]
The task is to find out if Babbage had the right answer — and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand.
As Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.
For these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].
Motivation
The aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.
| #Dafny | Dafny |
// Helper function for mask: does the actual computation.
function method mask_(v:int,m:int):int
decreases v-m
requires 0 <= v && 0 < m
ensures v < mask_(v,m)
{
if v < m then m else mask_(v,m*10)
}
// Return the smallest power of 10 greater than v.
function method mask(v:int):int
requires 0 <= v
ensures v < mask(v)
{
mask_(v,10)
}
// Return true if the last digits of v == suffix.
predicate method EndWith(v:int,suffix:int)
requires 0 <= suffix
{
v % mask(suffix) == suffix
}
method SmallestSqEndingWith(suffix:int) returns (s:int)
requires 0 < suffix
ensures EndWith(s*s, suffix)
// ensures forall i :: 0 <= i < s ==> !EndWith(i*i,suffix)
decreases * // This method may not terminate.
{
s := 0;
// squares is the sequence of s*s. A ghost variable is only used by the
// verification process at compile time.
ghost var squares := [];
while !EndWith(s*s, suffix)
invariant s == |squares|
invariant forall i :: 0 <= i < s ==> squares[i] == i*i && !EndWith(squares[i], suffix)
decreases *
{
squares := squares + [s*s];
s := s + 1;
}
// Leaving the method:
// s*s ends with the suffix.
assert EndWith(s*s, suffix);
// The sequence squares contains i*i for i in [0..s]; none of the elements of
// squares ends with the suffix.
assert s == |squares|;
assert forall i :: 0 <= i < s ==> i*i == squares[i] && !EndWith(squares[i], suffix);
// That last assertion should imply the commented-out post-condition of the
// method, but I'm not sure how to express that.
//
// Conclusion: s is guaranteed to be the smallest number whose square ends
// with the suffix.
}
method Main() decreases *
{
var suffix := 269696;
var smallest := SmallestSqEndingWith(suffix);
print smallest, "\n";
}
|
http://rosettacode.org/wiki/Averages/Simple_moving_average | Averages/Simple moving average | Computing the simple moving average of a series of numbers.
Task[edit]
Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far.
Description
A simple moving average is a method for computing an average of a stream of numbers by only averaging the last P numbers from the stream, where P is known as the period.
It can be implemented by calling an initialing routine with P as its argument, I(P), which should then return a routine that when called with individual, successive members of a stream of numbers, computes the mean of (up to), the last P of them, lets call this SMA().
The word stateful in the task description refers to the need for SMA() to remember certain information between calls to it:
The period, P
An ordered container of at least the last P numbers from each of its individual calls.
Stateful also means that successive calls to I(), the initializer, should return separate routines that do not share saved state so they could be used on two independent streams of data.
Pseudo-code for an implementation of SMA is:
function SMA(number: N):
stateful integer: P
stateful list: stream
number: average
stream.append_last(N)
if stream.length() > P:
# Only average the last P elements of the stream
stream.delete_first()
if stream.length() == 0:
average = 0
else:
average = sum( stream.values() ) / stream.length()
return average
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #GAP | GAP | MovingAverage := function(n)
local sma, buffer, pos, sum, len;
buffer := List([1 .. n], i -> 0);
pos := 0;
len := 0;
sum := 0;
sma := function(x)
pos := RemInt(pos, n) + 1;
sum := sum + x - buffer[pos];
buffer[pos] := x;
len := Minimum(len + 1, n);
return sum/len;
end;
return sma;
end;
f := MovingAverage(3);
f(1); # 1
f(2); # 3/2
f(3); # 2
f(4); # 3
f(5); # 4
f(5); # 14/3
f(4); # 14/3
f(3); # 4
f(2); # 3
f(1); # 2 |
http://rosettacode.org/wiki/Barnsley_fern | Barnsley fern |
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS).
Task
Create this fractal fern, using the following transformations:
ƒ1 (chosen 1% of the time)
xn + 1 = 0
yn + 1 = 0.16 yn
ƒ2 (chosen 85% of the time)
xn + 1 = 0.85 xn + 0.04 yn
yn + 1 = −0.04 xn + 0.85 yn + 1.6
ƒ3 (chosen 7% of the time)
xn + 1 = 0.2 xn − 0.26 yn
yn + 1 = 0.23 xn + 0.22 yn + 1.6
ƒ4 (chosen 7% of the time)
xn + 1 = −0.15 xn + 0.28 yn
yn + 1 = 0.26 xn + 0.24 yn + 0.44.
Starting position: x = 0, y = 0
| #REXX | REXX | /*REXX pgm gens X & Y coördinates for a scatter plot to be used to show a Barnsley fern.*/
parse arg N FID seed . /*obtain optional arguments from the CL*/
if N=='' | N=="," then N= 100000 /*Not specified? Then use the default*/
if FID=='' | FID=="," then FID= 'BARNSLEY.DAT' /* " " " " " " */
if datatype(seed,'W') then call random ,,seed /*if specified, then use random seed. */
call lineout FID, , 1 /*just set the file ptr to the 1st line*/
x=0 /*set the initial value for X coörd. */
y=0 /* " " " " " Y " */
do #=1 for N /*generate N number of plot points.*/
?=random(, 100) /*generate a random number: 0 ≤ ? ≤ 100*/
select
when ?==0 then do; xx= 0 ; yy= .16*y ; end
when ?< 8 then do; xx= .2 *x - .26*y; yy= .23*x + .22*y + 1.6 ; end
when ?<15 then do; xx= -.15*x + .28*y; yy= .26*x + .24*y + .44; end
otherwise xx= .85*x + .04*y; yy= -.04*x + .85*y + 1.6
end /*select*/
x=xx; y=yy
if #==1 then do; minx= x; maxx= x; miny= y; maxy= y
end
minx= min(minx, x); miny= min(miny, y)
maxx= max(maxx, x); maxy= max(maxy, y)
call lineout FID, x","y
end /*#*/ /* [↓] close the file (safe practice).*/
call lineout FID /*stick a fork in it, we're all done. */ |
http://rosettacode.org/wiki/Averages/Root_mean_square | Averages/Root mean square | Task[edit]
Compute the Root mean square of the numbers 1..10.
The root mean square is also known by its initials RMS (or rms), and as the quadratic mean.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
x
r
m
s
=
x
1
2
+
x
2
2
+
⋯
+
x
n
2
n
.
{\displaystyle x_{\mathrm {rms} }={\sqrt {{{x_{1}}^{2}+{x_{2}}^{2}+\cdots +{x_{n}}^{2}} \over n}}.}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Scheme | Scheme | (define (rms nums)
(sqrt (/ (apply + (map * nums nums))
(length nums))))
(rms '(1 2 3 4 5 6 7 8 9 10)) |
http://rosettacode.org/wiki/Averages/Root_mean_square | Averages/Root mean square | Task[edit]
Compute the Root mean square of the numbers 1..10.
The root mean square is also known by its initials RMS (or rms), and as the quadratic mean.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
x
r
m
s
=
x
1
2
+
x
2
2
+
⋯
+
x
n
2
n
.
{\displaystyle x_{\mathrm {rms} }={\sqrt {{{x_{1}}^{2}+{x_{2}}^{2}+\cdots +{x_{n}}^{2}} \over n}}.}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "float.s7i";
include "math.s7i";
const array float: numbers is [] (1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0);
const func float: rms (in array float: numbers) is func
result
var float: rms is 0.0;
local
var float: number is 0.0;
var float: sum is 0.0;
begin
for number range numbers do
sum +:= number ** 2;
end for;
rms := sqrt(sum / flt(length(numbers)));
end func;
const proc: main is func
begin
writeln(rms(numbers) digits 7);
end func; |
http://rosettacode.org/wiki/Babbage_problem | Babbage problem |
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
What is the smallest positive integer whose square ends in the digits 269,696?
— Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.
He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.
Task[edit]
The task is to find out if Babbage had the right answer — and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand.
As Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.
For these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].
Motivation
The aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.
| #Dart | Dart |
main() {
var x = 0;
while((x*x)% 1000000 != 269696)
{ x++;}
print('$x');
}
|
http://rosettacode.org/wiki/Averages/Simple_moving_average | Averages/Simple moving average | Computing the simple moving average of a series of numbers.
Task[edit]
Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far.
Description
A simple moving average is a method for computing an average of a stream of numbers by only averaging the last P numbers from the stream, where P is known as the period.
It can be implemented by calling an initialing routine with P as its argument, I(P), which should then return a routine that when called with individual, successive members of a stream of numbers, computes the mean of (up to), the last P of them, lets call this SMA().
The word stateful in the task description refers to the need for SMA() to remember certain information between calls to it:
The period, P
An ordered container of at least the last P numbers from each of its individual calls.
Stateful also means that successive calls to I(), the initializer, should return separate routines that do not share saved state so they could be used on two independent streams of data.
Pseudo-code for an implementation of SMA is:
function SMA(number: N):
stateful integer: P
stateful list: stream
number: average
stream.append_last(N)
if stream.length() > P:
# Only average the last P elements of the stream
stream.delete_first()
if stream.length() == 0:
average = 0
else:
average = sum( stream.values() ) / stream.length()
return average
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Go | Go | package main
import "fmt"
func sma(period int) func(float64) float64 {
var i int
var sum float64
var storage = make([]float64, 0, period)
return func(input float64) (avrg float64) {
if len(storage) < period {
sum += input
storage = append(storage, input)
}
sum += input - storage[i]
storage[i], i = input, (i+1)%period
avrg = sum / float64(len(storage))
return
}
}
func main() {
sma3 := sma(3)
sma5 := sma(5)
fmt.Println("x sma3 sma5")
for _, x := range []float64{1, 2, 3, 4, 5, 5, 4, 3, 2, 1} {
fmt.Printf("%5.3f %5.3f %5.3f\n", x, sma3(x), sma5(x))
}
} |
http://rosettacode.org/wiki/Barnsley_fern | Barnsley fern |
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS).
Task
Create this fractal fern, using the following transformations:
ƒ1 (chosen 1% of the time)
xn + 1 = 0
yn + 1 = 0.16 yn
ƒ2 (chosen 85% of the time)
xn + 1 = 0.85 xn + 0.04 yn
yn + 1 = −0.04 xn + 0.85 yn + 1.6
ƒ3 (chosen 7% of the time)
xn + 1 = 0.2 xn − 0.26 yn
yn + 1 = 0.23 xn + 0.22 yn + 1.6
ƒ4 (chosen 7% of the time)
xn + 1 = −0.15 xn + 0.28 yn
yn + 1 = 0.26 xn + 0.24 yn + 0.44.
Starting position: x = 0, y = 0
| #Ring | Ring |
Load "guilib.ring"
/*
+---------------------------------------------------------------------------
+ Program Name : Draw Barnsley Fern
+ Purpose : Draw Fern using Quadratic Equation and Random Number
+---------------------------------------------------------------------------
*/
###-------------------------------
### DRAW CHART size 400 x 500
###-------------------------------
New qapp {
win1 = new qwidget() {
### Position and Size on Screen
setwindowtitle("Drawing using QPainter")
setgeometry( 10, 25, 400, 500)
### Draw within this Win Box
label1 = new qlabel(win1) {
### Label Position and Size
setgeometry(10, 10, 400, 500)
settext(" ")
}
buttonFern = new qpushbutton(win1) {
### Button DrawFern
setgeometry(10, 10, 80, 20)
settext("Draw Fern")
setclickevent("DrawFern()") ### Call DRAW function
}
show()
}
exec()
}
###------------------------
### FUNCTIONS
###------------------------
Func DrawFern
p1 = new qpicture()
colorGreen = new qcolor() { setrgb(0,255,0,255) }
penGreen = new qpen() { setcolor(colorGreen) setwidth(1) }
new qpainter() {
begin(p1)
setpen(penGreen)
###-------------------------------------
### Quadratic equation matrix of arrays
a = [ 0, 0.85, 0.2, -0.15 ]
b = [ 0, 0.04, -0.26, 0.28 ]
c = [ 0, -0.04, 0.23, 0.26 ]
d = [ 0.16, 0.85, 0.22, 0.24 ]
e = [ 0, 0, 0, 0 ]
f = [ 0, 1.6, 1.6, 0.44 ]
### Initialize x, y points
xf = 0.0
yf = 0.0
### Size of output screen
MaxX = 400
MaxY = 500
MaxIterations = MaxY * 200
Count = 0
###------------------------------------------------
while ( Count <= MaxIterations )
### NOTE *** RING *** starts at Index 1,
### Do NOT use Random K=0 result
k = random() % 100
k = k +1
### if (k = 0) k = 1 ok ### Do NOT use
if ((k > 0) and (k <= 85)) k = 2 ok
if ((k > 85) and (k <= 92)) k = 3 ok
if (k > 92) k = 4 ok
TempX = ( a[k] * xf ) + ( b[k] * yf ) + e[k]
TempY = ( c[k] * xf ) + ( d[k] * yf ) + f[k]
xf = TempX
yf = TempY
if( (Count >= MaxIterations) or (Count != 0) )
xPoint = (floor(xf * MaxY / 11) + floor(MaxX / 2))
yPoint = (floor(yf * -MaxY / 11) + MaxY )
drawpoint( xPoint , yPoint )
ok
Count++
end
###----------------------------------------------------
endpaint()
}
label1 { setpicture(p1) show() }
return
|
http://rosettacode.org/wiki/Averages/Root_mean_square | Averages/Root mean square | Task[edit]
Compute the Root mean square of the numbers 1..10.
The root mean square is also known by its initials RMS (or rms), and as the quadratic mean.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
x
r
m
s
=
x
1
2
+
x
2
2
+
⋯
+
x
n
2
n
.
{\displaystyle x_{\mathrm {rms} }={\sqrt {{{x_{1}}^{2}+{x_{2}}^{2}+\cdots +{x_{n}}^{2}} \over n}}.}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Shen | Shen | (declare scm.sqrt [number --> number])
(tc +)
(define mean
{ (list number) --> number }
Xs -> (/ (sum Xs) (length Xs)))
(define square
{ number --> number }
X -> (* X X))
(define rms
{ (list number) --> number }
Xs -> (scm.sqrt (mean (map (function square) Xs))))
(define iota-h
{ number --> number --> (list number) }
X X -> [X]
X Lim -> (cons X (iota-h (+ X 1) Lim)))
(define iota
{ number --> (list number) }
Lim -> (iota-h 1 Lim))
(output "~A~%" (rms (iota 10))) |
http://rosettacode.org/wiki/Averages/Root_mean_square | Averages/Root mean square | Task[edit]
Compute the Root mean square of the numbers 1..10.
The root mean square is also known by its initials RMS (or rms), and as the quadratic mean.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
x
r
m
s
=
x
1
2
+
x
2
2
+
⋯
+
x
n
2
n
.
{\displaystyle x_{\mathrm {rms} }={\sqrt {{{x_{1}}^{2}+{x_{2}}^{2}+\cdots +{x_{n}}^{2}} \over n}}.}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Sidef | Sidef | func rms(a) {
sqrt(a.map{.**2}.sum / a.len)
}
say rms(1..10) |
http://rosettacode.org/wiki/Babbage_problem | Babbage problem |
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
What is the smallest positive integer whose square ends in the digits 269,696?
— Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.
He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.
Task[edit]
The task is to find out if Babbage had the right answer — and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand.
As Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.
For these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].
Motivation
The aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.
| #Delphi | Delphi | var i = 0
while i * i % 1000000 != 269696 {
i += 1
}
print("\(i) is the smallest number that ends with 269696") |
http://rosettacode.org/wiki/Babbage_problem | Babbage problem |
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
What is the smallest positive integer whose square ends in the digits 269,696?
— Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.
He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.
Task[edit]
The task is to find out if Babbage had the right answer — and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand.
As Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.
For these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].
Motivation
The aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.
| #Dyalect | Dyalect | var i = 0
while i * i % 1000000 != 269696 {
i += 1
}
print("\(i) is the smallest number that ends with 269696") |
http://rosettacode.org/wiki/Averages/Simple_moving_average | Averages/Simple moving average | Computing the simple moving average of a series of numbers.
Task[edit]
Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far.
Description
A simple moving average is a method for computing an average of a stream of numbers by only averaging the last P numbers from the stream, where P is known as the period.
It can be implemented by calling an initialing routine with P as its argument, I(P), which should then return a routine that when called with individual, successive members of a stream of numbers, computes the mean of (up to), the last P of them, lets call this SMA().
The word stateful in the task description refers to the need for SMA() to remember certain information between calls to it:
The period, P
An ordered container of at least the last P numbers from each of its individual calls.
Stateful also means that successive calls to I(), the initializer, should return separate routines that do not share saved state so they could be used on two independent streams of data.
Pseudo-code for an implementation of SMA is:
function SMA(number: N):
stateful integer: P
stateful list: stream
number: average
stream.append_last(N)
if stream.length() > P:
# Only average the last P elements of the stream
stream.delete_first()
if stream.length() == 0:
average = 0
else:
average = sum( stream.values() ) / stream.length()
return average
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Groovy | Groovy | def simple_moving_average = { size ->
def nums = []
double total = 0.0
return { newElement ->
nums += newElement
oldestElement = nums.size() > size ? nums.remove(0) : 0
total += newElement - oldestElement
total / nums.size()
}
}
ma5 = simple_moving_average(5)
(1..5).each{ printf( "%1.1f ", ma5(it)) }
(5..1).each{ printf( "%1.1f ", ma5(it)) } |
http://rosettacode.org/wiki/Averages/Pythagorean_means | Averages/Pythagorean means | Task[edit]
Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive).
Show that
A
(
x
1
,
…
,
x
n
)
≥
G
(
x
1
,
…
,
x
n
)
≥
H
(
x
1
,
…
,
x
n
)
{\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})}
for this set of positive integers.
The most common of the three means, the arithmetic mean, is the sum of the list divided by its length:
A
(
x
1
,
…
,
x
n
)
=
x
1
+
⋯
+
x
n
n
{\displaystyle A(x_{1},\ldots ,x_{n})={\frac {x_{1}+\cdots +x_{n}}{n}}}
The geometric mean is the
n
{\displaystyle n}
th root of the product of the list:
G
(
x
1
,
…
,
x
n
)
=
x
1
⋯
x
n
n
{\displaystyle G(x_{1},\ldots ,x_{n})={\sqrt[{n}]{x_{1}\cdots x_{n}}}}
The harmonic mean is
n
{\displaystyle n}
divided by the sum of the reciprocal of each item in the list:
H
(
x
1
,
…
,
x
n
)
=
n
1
x
1
+
⋯
+
1
x
n
{\displaystyle H(x_{1},\ldots ,x_{n})={\frac {n}{{\frac {1}{x_{1}}}+\cdots +{\frac {1}{x_{n}}}}}}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #11l | 11l | F amean(num)
R sum(num)/Float(num.len)
F gmean(num)
R product(num) ^ (1.0/num.len)
F hmean(num)
return num.len / sum(num.map(n -> 1.0/n))
V numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(amean(numbers))
print(gmean(numbers))
print(hmean(numbers)) |
http://rosettacode.org/wiki/Barnsley_fern | Barnsley fern |
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS).
Task
Create this fractal fern, using the following transformations:
ƒ1 (chosen 1% of the time)
xn + 1 = 0
yn + 1 = 0.16 yn
ƒ2 (chosen 85% of the time)
xn + 1 = 0.85 xn + 0.04 yn
yn + 1 = −0.04 xn + 0.85 yn + 1.6
ƒ3 (chosen 7% of the time)
xn + 1 = 0.2 xn − 0.26 yn
yn + 1 = 0.23 xn + 0.22 yn + 1.6
ƒ4 (chosen 7% of the time)
xn + 1 = −0.15 xn + 0.28 yn
yn + 1 = 0.26 xn + 0.24 yn + 0.44.
Starting position: x = 0, y = 0
| #Ruby | Ruby |
MAX_ITERATIONS = 200_000
def setup
sketch_title 'Barnsley Fern'
no_loop
puts 'Be patient. This takes about 10 seconds to render.'
end
def draw
background 0
load_pixels
x0 = 0.0
y0 = 0.0
x = 0.0
y = 0.0
MAX_ITERATIONS.times do
r = rand(100)
if r < 85
x = 0.85 * x0 + 0.04 * y0
y = -0.04 * x0 + 0.85 * y0 + 1.6
elsif r < 92
x = 0.2 * x0 - 0.26 * y0
y = 0.23 * x0 + 0.22 * y0 + 1.6
elsif r < 99
x = -0.15 * x0 + 0.28 * y0
y = 0.26 * x0 + 0.24 * y0 + 0.44
else
x = 0
y = 0.16 * y
end
i = height - (y * 48).to_i
j = width / 2 + (x * 48).to_i
pixels[i * height + j] += 2_560
x0 = x
y0 = y
end
update_pixels
end
def settings
size 500, 500
end
|
http://rosettacode.org/wiki/Averages/Root_mean_square | Averages/Root mean square | Task[edit]
Compute the Root mean square of the numbers 1..10.
The root mean square is also known by its initials RMS (or rms), and as the quadratic mean.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
x
r
m
s
=
x
1
2
+
x
2
2
+
⋯
+
x
n
2
n
.
{\displaystyle x_{\mathrm {rms} }={\sqrt {{{x_{1}}^{2}+{x_{2}}^{2}+\cdots +{x_{n}}^{2}} \over n}}.}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Smalltalk | Smalltalk | (((1 to: 10) inject: 0 into: [ :s :n | n*n + s ]) / 10) sqrt. |
http://rosettacode.org/wiki/Averages/Root_mean_square | Averages/Root mean square | Task[edit]
Compute the Root mean square of the numbers 1..10.
The root mean square is also known by its initials RMS (or rms), and as the quadratic mean.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
x
r
m
s
=
x
1
2
+
x
2
2
+
⋯
+
x
n
2
n
.
{\displaystyle x_{\mathrm {rms} }={\sqrt {{{x_{1}}^{2}+{x_{2}}^{2}+\cdots +{x_{n}}^{2}} \over n}}.}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #SNOBOL4 | SNOBOL4 | define('rms(a)i,ssq') :(rms_end)
rms i = i + 1; ssq = ssq + (a<i> * a<i>) :s(rms)
rms = sqrt(1.0 * ssq / prototype(a)) :(return)
rms_end
* # Fill array, test and display
str = '1 2 3 4 5 6 7 8 9 10'; a = array(10)
loop i = i + 1; str len(p) span('0123456789') . a<i> @p :s(loop)
output = str ' -> ' rms(a)
end |
http://rosettacode.org/wiki/Babbage_problem | Babbage problem |
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
What is the smallest positive integer whose square ends in the digits 269,696?
— Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.
He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.
Task[edit]
The task is to find out if Babbage had the right answer — and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand.
As Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.
For these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].
Motivation
The aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.
| #EasyLang | EasyLang | while n * n mod 1000000 <> 269696
n += 1
.
print n |
http://rosettacode.org/wiki/Averages/Simple_moving_average | Averages/Simple moving average | Computing the simple moving average of a series of numbers.
Task[edit]
Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far.
Description
A simple moving average is a method for computing an average of a stream of numbers by only averaging the last P numbers from the stream, where P is known as the period.
It can be implemented by calling an initialing routine with P as its argument, I(P), which should then return a routine that when called with individual, successive members of a stream of numbers, computes the mean of (up to), the last P of them, lets call this SMA().
The word stateful in the task description refers to the need for SMA() to remember certain information between calls to it:
The period, P
An ordered container of at least the last P numbers from each of its individual calls.
Stateful also means that successive calls to I(), the initializer, should return separate routines that do not share saved state so they could be used on two independent streams of data.
Pseudo-code for an implementation of SMA is:
function SMA(number: N):
stateful integer: P
stateful list: stream
number: average
stream.append_last(N)
if stream.length() > P:
# Only average the last P elements of the stream
stream.delete_first()
if stream.length() == 0:
average = 0
else:
average = sum( stream.values() ) / stream.length()
return average
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Haskell | Haskell | {-# LANGUAGE BangPatterns #-}
import Control.Monad
import Data.List
import Data.IORef
data Pair a b = Pair !a !b
mean :: Fractional a => [a] -> a
mean = divl . foldl' (\(Pair s l) x -> Pair (s+x) (l+1)) (Pair 0.0 0)
where divl (_,0) = 0.0
divl (s,l) = s / fromIntegral l
series = [1,2,3,4,5,5,4,3,2,1]
mkSMA :: Int -> IO (Double -> IO Double)
mkSMA period = avgr <$> newIORef []
where avgr nsref x = readIORef nsref >>= (\ns ->
let xs = take period (x:ns)
in writeIORef nsref xs $> mean xs)
main = mkSMA 3 >>= (\sma3 -> mkSMA 5 >>= (\sma5 ->
mapM_ (str <$> pure n <*> sma3 <*> sma5) series))
where str n mm3 mm5 =
concat ["Next number = ",show n,", SMA_3 = ",show mm3,", SMA_5 = ",show mm5] |
http://rosettacode.org/wiki/Averages/Pythagorean_means | Averages/Pythagorean means | Task[edit]
Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive).
Show that
A
(
x
1
,
…
,
x
n
)
≥
G
(
x
1
,
…
,
x
n
)
≥
H
(
x
1
,
…
,
x
n
)
{\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})}
for this set of positive integers.
The most common of the three means, the arithmetic mean, is the sum of the list divided by its length:
A
(
x
1
,
…
,
x
n
)
=
x
1
+
⋯
+
x
n
n
{\displaystyle A(x_{1},\ldots ,x_{n})={\frac {x_{1}+\cdots +x_{n}}{n}}}
The geometric mean is the
n
{\displaystyle n}
th root of the product of the list:
G
(
x
1
,
…
,
x
n
)
=
x
1
⋯
x
n
n
{\displaystyle G(x_{1},\ldots ,x_{n})={\sqrt[{n}]{x_{1}\cdots x_{n}}}}
The harmonic mean is
n
{\displaystyle n}
divided by the sum of the reciprocal of each item in the list:
H
(
x
1
,
…
,
x
n
)
=
n
1
x
1
+
⋯
+
1
x
n
{\displaystyle H(x_{1},\ldots ,x_{n})={\frac {n}{{\frac {1}{x_{1}}}+\cdots +{\frac {1}{x_{n}}}}}}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Action.21 | Action! | INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
PROC InverseI(INT a,result)
REAL one,x
IntToReal(1,one)
IntToReal(a,x)
RealDiv(one,x,result)
RETURN
PROC ArithmeticMean(INT ARRAY a INT count REAL POINTER result)
INT i
REAL x,sum,tmp
IntToReal(0,sum)
FOR i=0 TO count-1
DO
IntToReal(a(i),x)
RealAdd(sum,x,tmp)
RealAssign(tmp,sum)
OD
IntToReal(count,tmp)
RealDiv(sum,tmp,result)
RETURN
PROC GeometricMean(INT ARRAY a INT count REAL POINTER result)
INT i
REAL x,prod,tmp
IntToReal(1,prod)
FOR i=0 TO count-1
DO
IntToReal(a(i),x)
RealMult(prod,x,tmp)
RealAssign(tmp,prod)
OD
InverseI(count,tmp)
Power(prod,tmp,result)
RETURN
PROC HarmonicMean(INT ARRAY a INT count REAL POINTER result)
INT i
REAL x,sum,tmp
IntToReal(0,sum)
FOR i=0 TO count-1
DO
InverseI(a(i),x)
RealAdd(sum,x,tmp)
RealAssign(tmp,sum)
OD
IntToReal(count,tmp)
RealDiv(tmp,sum,result)
RETURN
PROC Main()
BYTE i
INT ARRAY a=[1 2 3 4 5 6 7 8 9 10]
REAL result
Put(125) PutE() ;clear screen
ArithmeticMean(a,10,result)
Print("Arithmetic mean=") PrintRE(result)
GeometricMean(a,10,result)
Print(" Geometric mean=") PrintRE(result)
HarmonicMean(a,10,result)
Print(" Harmonic mean=") PrintRE(result)
RETURN |
http://rosettacode.org/wiki/Barnsley_fern | Barnsley fern |
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS).
Task
Create this fractal fern, using the following transformations:
ƒ1 (chosen 1% of the time)
xn + 1 = 0
yn + 1 = 0.16 yn
ƒ2 (chosen 85% of the time)
xn + 1 = 0.85 xn + 0.04 yn
yn + 1 = −0.04 xn + 0.85 yn + 1.6
ƒ3 (chosen 7% of the time)
xn + 1 = 0.2 xn − 0.26 yn
yn + 1 = 0.23 xn + 0.22 yn + 1.6
ƒ4 (chosen 7% of the time)
xn + 1 = −0.15 xn + 0.28 yn
yn + 1 = 0.26 xn + 0.24 yn + 0.44.
Starting position: x = 0, y = 0
| #Run_BASIC | Run BASIC | 'Barnsley Fern - Run BASIC
'http://rosettacode.org/wiki/Barnsley_fern#Run_BASIC
'copy code and run it at http://www.runbasic.com
'
' -----------------------------------
' Barnsley Fern
' -----------------------------------maxpoints = 20000
graphic #g, 200, 200
#g fill("blue")
FOR n = 1 TO maxpoints
p = RND(0)*100
IF p <= 1 THEN
nx = 0
ny = 0.16 * y
else if p <= 8 THEN
nx = 0.2 * x - 0.26 * y
ny = 0.23 * x + 0.22 * y + 1.6
else if p <= 15 THEN
nx = -0.15 * x + 0.28 * y
ny = 0.26 * x + 0.24 * y + 0.44
else
nx = 0.85 * x +0.04 * y
ny = -0.04 * x +0.85 * y + 1.6
end if
x = nx
y = ny
#g "color green ; set "; x * 17 + 100; " "; y * 17
NEXT n
render #g
#g "flush" |
http://rosettacode.org/wiki/Barnsley_fern | Barnsley fern |
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS).
Task
Create this fractal fern, using the following transformations:
ƒ1 (chosen 1% of the time)
xn + 1 = 0
yn + 1 = 0.16 yn
ƒ2 (chosen 85% of the time)
xn + 1 = 0.85 xn + 0.04 yn
yn + 1 = −0.04 xn + 0.85 yn + 1.6
ƒ3 (chosen 7% of the time)
xn + 1 = 0.2 xn − 0.26 yn
yn + 1 = 0.23 xn + 0.22 yn + 1.6
ƒ4 (chosen 7% of the time)
xn + 1 = −0.15 xn + 0.28 yn
yn + 1 = 0.26 xn + 0.24 yn + 0.44.
Starting position: x = 0, y = 0
| #Rust | Rust | extern crate rand;
extern crate raster;
use rand::Rng;
fn main() {
let max_iterations = 200_000u32;
let height = 640i32;
let width = 640i32;
let mut rng = rand::thread_rng();
let mut image = raster::Image::blank(width, height);
raster::editor::fill(&mut image, raster::Color::white()).unwrap();
let mut x = 0.;
let mut y = 0.;
for _ in 0..max_iterations {
let r = rng.gen::<f32>();
let cx: f64;
let cy: f64;
if r <= 0.01 {
cx = 0f64;
cy = 0.16 * y as f64;
} else if r <= 0.08 {
cx = 0.2 * x as f64 - 0.26 * y as f64;
cy = 0.23 * x as f64 + 0.22 * y as f64 + 1.6;
} else if r <= 0.15 {
cx = -0.15 * x as f64 + 0.28 * y as f64;
cy = 0.26 * x as f64 + 0.26 * y as f64 + 0.44;
} else {
cx = 0.85 * x as f64 + 0.04 * y as f64;
cy = -0.04 * x as f64 + 0.85 * y as f64 + 1.6;
}
x = cx;
y = cy;
let _ = image.set_pixel(
((width as f64) / 2. + x * (width as f64) / 11.).round() as i32,
((height as f64) - y * (height as f64) / 11.).round() as i32,
raster::Color::rgb(50, 205, 50));
}
raster::save(&image, "fractal.png").unwrap();
} |
http://rosettacode.org/wiki/Averages/Root_mean_square | Averages/Root mean square | Task[edit]
Compute the Root mean square of the numbers 1..10.
The root mean square is also known by its initials RMS (or rms), and as the quadratic mean.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
x
r
m
s
=
x
1
2
+
x
2
2
+
⋯
+
x
n
2
n
.
{\displaystyle x_{\mathrm {rms} }={\sqrt {{{x_{1}}^{2}+{x_{2}}^{2}+\cdots +{x_{n}}^{2}} \over n}}.}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Standard_ML | Standard ML | fun rms(v: real vector) =
let
val v' = Vector.map (fn x => x*x) v
val sum = Vector.foldl op+ 0.0 v'
in
Math.sqrt( sum/real(Vector.length(v')) )
end;
rms(Vector.tabulate(10, fn n => real(n+1))); |
http://rosettacode.org/wiki/Averages/Root_mean_square | Averages/Root mean square | Task[edit]
Compute the Root mean square of the numbers 1..10.
The root mean square is also known by its initials RMS (or rms), and as the quadratic mean.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
x
r
m
s
=
x
1
2
+
x
2
2
+
⋯
+
x
n
2
n
.
{\displaystyle x_{\mathrm {rms} }={\sqrt {{{x_{1}}^{2}+{x_{2}}^{2}+\cdots +{x_{n}}^{2}} \over n}}.}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Stata | Stata | program rms, rclass
syntax varname(numeric) [if] [in]
tempvar x
gen `x'=`varlist'^2 `if' `in'
qui sum `x' `if' `in'
return scalar rms=sqrt(r(mean))
end |
http://rosettacode.org/wiki/Babbage_problem | Babbage problem |
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
What is the smallest positive integer whose square ends in the digits 269,696?
— Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.
He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.
Task[edit]
The task is to find out if Babbage had the right answer — and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand.
As Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.
For these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].
Motivation
The aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.
| #EDSAC_order_code | EDSAC order code |
[Babbage problem from Rosetta Code website]
[EDSAC program, Initial Orders 2]
[Library subroutine M3. Pauses the loading, prints header,
and gets overwritten when loading resumes.
Here, the last character sets the teleprinter to figures.]
PFGKIFAFRDLFUFOFE@A6FG@E8FEZPF
@&*SOLUTION!TO!BABBAGE!PROBLEM@&#
..PZ [blank tape, needed to mark end of header text]
[Library subroutine P6. Prints strictly positive integer.
32 locations; argument at 0, working locations 1, 4, 5]
T56K [define load address for subroutine]
GKA3FT25@H29@VFT4DA3@TFH30@S6@T1FV4DU4DAFG26@
TFTFO5FA4DF4FS4FL4FT4DA1FS3@G9@EFSFO31@E20@J995FJF!F
[Main routine. Load after subroutine P6.
Must be at an even address because each double
value at the start must be at an even address.]
T88K [define absolute load address]
GK [set @ (theta) for relative addresses]
[Variables]
[0] PF PF [trial solution, call it n]
[2] PF PF [residue of n^2 modulo 1000000]
[4] PF PF [1st difference for n^2]
[Constants]
[6] P64F PF [2nd difference for n^2, i.e. 128]
[8] P4F PF [1st difference for n, i.e. 8]
T10#Z PF T10Z [clears sandwich digit between 10 and 11;
cf. Wilkes, Wheeler & Gill, 1951, pp 110, 141-2]
[10] #1760F V2046F [-1000000]
T12#Z PF T12Z [clears sandwich digit between 12 and 13]
[12] Q1728F PD [269696]
[14] &F [line feed]
[15] @F [carriage return]
[16] K4096F [teleprinter null]
[Enter with acc = 0]
[17] T#@ [trial number n := 0]
T2#@ [(n^2 mod 1000000) := 0]
S6#@ [acc := -128]
RD [right shift]
T4#@ [(1st difference for n^2) := -64]
[Start of loop]
[22] TF [clear acc]
A#@ [load n]
A8#@ [add 8]
T#@ [update n]
A4#@ [load 1st difference of n^2]
A6#@ [add 128]
T4#@ [update]
A2#@ [load residue of n^2 mod 1000000]
A4#@ [add 1st difference]
[31] A10#@ [subtract 1000000, by adding -1000000]
E31@ [repeat until result < 0]
S10#@ [add back 1000000]
U2#@ [update residue]
S12#@ [subtract target 269696]
G22@ [loop back if residue < 269696]
[if still here, acc is non-neg mult of 64]
S8#@ [test for acc = 0 by subtracting 8]
E22@ [loop back if residue > 269696]
[Here with the solution]
TF [clear acc]
A#@ [load solution n]
TD [store at absolute address 0 for printing]
[42] A42@ [for return from subroutine]
G56F [call subroutine to print n]
O15@ [print CR]
O14@ [print LF]
O16@ [print null, to flush printer buffer]
ZF [stop]
E17Z [define entry point]
PF [enter with acc = 0]
|
http://rosettacode.org/wiki/Averages/Simple_moving_average | Averages/Simple moving average | Computing the simple moving average of a series of numbers.
Task[edit]
Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far.
Description
A simple moving average is a method for computing an average of a stream of numbers by only averaging the last P numbers from the stream, where P is known as the period.
It can be implemented by calling an initialing routine with P as its argument, I(P), which should then return a routine that when called with individual, successive members of a stream of numbers, computes the mean of (up to), the last P of them, lets call this SMA().
The word stateful in the task description refers to the need for SMA() to remember certain information between calls to it:
The period, P
An ordered container of at least the last P numbers from each of its individual calls.
Stateful also means that successive calls to I(), the initializer, should return separate routines that do not share saved state so they could be used on two independent streams of data.
Pseudo-code for an implementation of SMA is:
function SMA(number: N):
stateful integer: P
stateful list: stream
number: average
stream.append_last(N)
if stream.length() > P:
# Only average the last P elements of the stream
stream.delete_first()
if stream.length() == 0:
average = 0
else:
average = sum( stream.values() ) / stream.length()
return average
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #HicEst | HicEst | REAL :: n=10, nums(n)
nums = (1,2,3,4,5, 5,4,3,2,1)
DO i = 1, n
WRITE() "num=", i, "SMA3=", SMA(3,nums(i)), "SMA5=",SMA(5,nums(i))
ENDDO
END ! of "main"
FUNCTION SMA(period, num) ! maxID independent streams
REAL :: maxID=10, now(maxID), Periods(maxID), Offsets(maxID), Pool(1000)
ID = INDEX(Periods, period)
IF( ID == 0) THEN ! initialization
IDs = IDs + 1
ID = IDs
Offsets(ID) = SUM(Periods) + 1
Periods(ID) = period
ENDIF
now(ID) = now(ID) + 1
ALIAS(Pool,Offsets(ID), Past,Periods(ID)) ! renames relevant part of data pool
Past = Past($+1) ! shift left
Past(Periods(ID)) = num
SMA = SUM(Past) / MIN( now(ID), Periods(ID) )
END |
http://rosettacode.org/wiki/Averages/Pythagorean_means | Averages/Pythagorean means | Task[edit]
Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive).
Show that
A
(
x
1
,
…
,
x
n
)
≥
G
(
x
1
,
…
,
x
n
)
≥
H
(
x
1
,
…
,
x
n
)
{\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})}
for this set of positive integers.
The most common of the three means, the arithmetic mean, is the sum of the list divided by its length:
A
(
x
1
,
…
,
x
n
)
=
x
1
+
⋯
+
x
n
n
{\displaystyle A(x_{1},\ldots ,x_{n})={\frac {x_{1}+\cdots +x_{n}}{n}}}
The geometric mean is the
n
{\displaystyle n}
th root of the product of the list:
G
(
x
1
,
…
,
x
n
)
=
x
1
⋯
x
n
n
{\displaystyle G(x_{1},\ldots ,x_{n})={\sqrt[{n}]{x_{1}\cdots x_{n}}}}
The harmonic mean is
n
{\displaystyle n}
divided by the sum of the reciprocal of each item in the list:
H
(
x
1
,
…
,
x
n
)
=
n
1
x
1
+
⋯
+
1
x
n
{\displaystyle H(x_{1},\ldots ,x_{n})={\frac {n}{{\frac {1}{x_{1}}}+\cdots +{\frac {1}{x_{n}}}}}}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #ActionScript | ActionScript | function arithmeticMean(v:Vector.<Number>):Number
{
var sum:Number = 0;
for(var i: uint = 0; i < v.length; i++)
sum += v[i];
return sum/v.length;
}
function geometricMean(v:Vector.<Number>):Number
{
var product:Number = 1;
for(var i: uint = 0; i < v.length; i++)
product *= v[i];
return Math.pow(product, 1/v.length);
}
function harmonicMean(v:Vector.<Number>):Number
{
var sum:Number = 0;
for(var i: uint = 0; i < v.length; i++)
sum += 1/v[i];
return v.length/sum;
}
var list:Vector.<Number> = Vector.<Number>([1,2,3,4,5,6,7,8,9,10]);
trace("Arithmetic: ", arithmeticMean(list));
trace("Geometric: ", geometricMean(list));
trace("Harmonic: ", harmonicMean(list)); |
http://rosettacode.org/wiki/Barnsley_fern | Barnsley fern |
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS).
Task
Create this fractal fern, using the following transformations:
ƒ1 (chosen 1% of the time)
xn + 1 = 0
yn + 1 = 0.16 yn
ƒ2 (chosen 85% of the time)
xn + 1 = 0.85 xn + 0.04 yn
yn + 1 = −0.04 xn + 0.85 yn + 1.6
ƒ3 (chosen 7% of the time)
xn + 1 = 0.2 xn − 0.26 yn
yn + 1 = 0.23 xn + 0.22 yn + 1.6
ƒ4 (chosen 7% of the time)
xn + 1 = −0.15 xn + 0.28 yn
yn + 1 = 0.26 xn + 0.24 yn + 0.44.
Starting position: x = 0, y = 0
| #Scala | Scala | import java.awt._
import java.awt.image.BufferedImage
import javax.swing._
object BarnsleyFern extends App {
SwingUtilities.invokeLater(() =>
new JFrame("Barnsley Fern") {
private class BarnsleyFern extends JPanel {
val dim = 640
val img = new BufferedImage(dim, dim, BufferedImage.TYPE_INT_ARGB)
private def createFern(w: Int, h: Int): Unit = {
var x, y = 0.0
for (i <- 0 until 200000) {
var tmpx, tmpy = .0
val r = math.random
if (r <= 0.01) {
tmpx = 0
tmpy = 0.16 * y
}
else if (r <= 0.08) {
tmpx = 0.2 * x - 0.26 * y
tmpy = 0.23 * x + 0.22 * y + 1.6
}
else if (r <= 0.15) {
tmpx = -0.15 * x + 0.28 * y
tmpy = 0.26 * x + 0.24 * y + 0.44
}
else {
tmpx = 0.85 * x + 0.04 * y
tmpy = -0.04 * x + 0.85 * y + 1.6
}
x = tmpx
y = tmpy
img.setRGB((w / 2 + tmpx * w / 11).round.toInt,
(h - tmpy * h / 11).round.toInt, 0xFF32CD32)
}
}
override def paintComponent(gg: Graphics): Unit = {
super.paintComponent(gg)
val g = gg.asInstanceOf[Graphics2D]
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
g.drawImage(img, 0, 0, null)
}
setBackground(Color.white)
setPreferredSize(new Dimension(dim, dim))
createFern(dim, dim)
}
add(new BarnsleyFern, BorderLayout.CENTER)
pack()
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)
setLocationRelativeTo(null)
setResizable(false)
setVisible(true)
})
} |
http://rosettacode.org/wiki/Averages/Root_mean_square | Averages/Root mean square | Task[edit]
Compute the Root mean square of the numbers 1..10.
The root mean square is also known by its initials RMS (or rms), and as the quadratic mean.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
x
r
m
s
=
x
1
2
+
x
2
2
+
⋯
+
x
n
2
n
.
{\displaystyle x_{\mathrm {rms} }={\sqrt {{{x_{1}}^{2}+{x_{2}}^{2}+\cdots +{x_{n}}^{2}} \over n}}.}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Swift | Swift | extension Collection where Element: FloatingPoint {
@inlinable
public func rms() -> Element {
return (lazy.map({ $0 * $0 }).reduce(0, +) / Element(count)).squareRoot()
}
}
print("RMS of 1...10: \((1...10).map(Double.init).rms())") |
http://rosettacode.org/wiki/Averages/Root_mean_square | Averages/Root mean square | Task[edit]
Compute the Root mean square of the numbers 1..10.
The root mean square is also known by its initials RMS (or rms), and as the quadratic mean.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
x
r
m
s
=
x
1
2
+
x
2
2
+
⋯
+
x
n
2
n
.
{\displaystyle x_{\mathrm {rms} }={\sqrt {{{x_{1}}^{2}+{x_{2}}^{2}+\cdots +{x_{n}}^{2}} \over n}}.}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Tcl | Tcl | proc qmean list {
set sum 0.0
foreach value $list { set sum [expr {$sum + $value**2}] }
return [expr { sqrt($sum / [llength $list]) }]
}
puts "RMS(1..10) = [qmean {1 2 3 4 5 6 7 8 9 10}]" |
http://rosettacode.org/wiki/Babbage_problem | Babbage problem |
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
What is the smallest positive integer whose square ends in the digits 269,696?
— Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.
He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.
Task[edit]
The task is to find out if Babbage had the right answer — and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand.
As Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.
For these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].
Motivation
The aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.
| #Elena | Elena | import extensions;
import system'math;
public program()
{
var n := 1;
until(n.sqr().mod:1000000 == 269696)
{
n += 1
};
console.printLine(n)
} |
http://rosettacode.org/wiki/Averages/Simple_moving_average | Averages/Simple moving average | Computing the simple moving average of a series of numbers.
Task[edit]
Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far.
Description
A simple moving average is a method for computing an average of a stream of numbers by only averaging the last P numbers from the stream, where P is known as the period.
It can be implemented by calling an initialing routine with P as its argument, I(P), which should then return a routine that when called with individual, successive members of a stream of numbers, computes the mean of (up to), the last P of them, lets call this SMA().
The word stateful in the task description refers to the need for SMA() to remember certain information between calls to it:
The period, P
An ordered container of at least the last P numbers from each of its individual calls.
Stateful also means that successive calls to I(), the initializer, should return separate routines that do not share saved state so they could be used on two independent streams of data.
Pseudo-code for an implementation of SMA is:
function SMA(number: N):
stateful integer: P
stateful list: stream
number: average
stream.append_last(N)
if stream.length() > P:
# Only average the last P elements of the stream
stream.delete_first()
if stream.length() == 0:
average = 0
else:
average = sum( stream.values() ) / stream.length()
return average
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Icon_and_Unicon | Icon and Unicon | procedure main(A)
sma := buildSMA(3) # Use better name than "I".
every write(sma(!A))
end
procedure buildSMA(P)
local stream
c := create {
stream := []
while n := (avg@&source)[1] do {
put(stream, n)
if *stream > P then pop(stream)
every (avg := 0.0) +:= !stream
avg := avg/*stream
}
}
return (@c, c)
end |
http://rosettacode.org/wiki/Averages/Pythagorean_means | Averages/Pythagorean means | Task[edit]
Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive).
Show that
A
(
x
1
,
…
,
x
n
)
≥
G
(
x
1
,
…
,
x
n
)
≥
H
(
x
1
,
…
,
x
n
)
{\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})}
for this set of positive integers.
The most common of the three means, the arithmetic mean, is the sum of the list divided by its length:
A
(
x
1
,
…
,
x
n
)
=
x
1
+
⋯
+
x
n
n
{\displaystyle A(x_{1},\ldots ,x_{n})={\frac {x_{1}+\cdots +x_{n}}{n}}}
The geometric mean is the
n
{\displaystyle n}
th root of the product of the list:
G
(
x
1
,
…
,
x
n
)
=
x
1
⋯
x
n
n
{\displaystyle G(x_{1},\ldots ,x_{n})={\sqrt[{n}]{x_{1}\cdots x_{n}}}}
The harmonic mean is
n
{\displaystyle n}
divided by the sum of the reciprocal of each item in the list:
H
(
x
1
,
…
,
x
n
)
=
n
1
x
1
+
⋯
+
1
x
n
{\displaystyle H(x_{1},\ldots ,x_{n})={\frac {n}{{\frac {1}{x_{1}}}+\cdots +{\frac {1}{x_{n}}}}}}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Ada | Ada | package Pythagorean_Means is
type Set is array (Positive range <>) of Float;
function Arithmetic_Mean (Data : Set) return Float;
function Geometric_Mean (Data : Set) return Float;
function Harmonic_Mean (Data : Set) return Float;
end Pythagorean_Means; |
http://rosettacode.org/wiki/Barnsley_fern | Barnsley fern |
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS).
Task
Create this fractal fern, using the following transformations:
ƒ1 (chosen 1% of the time)
xn + 1 = 0
yn + 1 = 0.16 yn
ƒ2 (chosen 85% of the time)
xn + 1 = 0.85 xn + 0.04 yn
yn + 1 = −0.04 xn + 0.85 yn + 1.6
ƒ3 (chosen 7% of the time)
xn + 1 = 0.2 xn − 0.26 yn
yn + 1 = 0.23 xn + 0.22 yn + 1.6
ƒ4 (chosen 7% of the time)
xn + 1 = −0.15 xn + 0.28 yn
yn + 1 = 0.26 xn + 0.24 yn + 0.44.
Starting position: x = 0, y = 0
| #Scheme | Scheme | (import (scheme base)
(scheme cxr)
(scheme file)
(scheme inexact)
(scheme write)
(srfi 27)) ; for random numbers
(define (create-fern x y num-points)
(define (new-point xn yn)
(let ((r (* 100 (random-real))))
(cond ((< r 1) ; f1
(list 0 (* 0.16 yn)))
((< r 86) ; f2
(list (+ (* 0.85 xn) (* 0.04 yn))
(+ (* -0.04 xn) (* 0.85 yn) 1.6)))
((< r 93) ; f3
(list (- (* 0.2 xn) (* 0.26 yn))
(+ (* 0.23 xn) (* 0.22 yn) 1.6)))
(else ; f4
(list (+ (* -0.15 xn) (* 0.28 yn))
(+ (* 0.26 xn) (* 0.24 yn) 0.44))))))
;
(random-source-randomize! default-random-source)
(do ((i 0 (+ i 1))
(pts (list (list x y)) (cons (new-point (caar pts) (cadar pts)) pts)))
((= i num-points) pts)))
;; output the fern to an eps file
(define (output-fern-as-eps filename fern)
(when (file-exists? filename) (delete-file filename))
(with-output-to-file
filename
(lambda ()
(let* ((width 600)
(height 800)
(min-x (apply min (map car fern)))
(max-x (apply max (map car fern)))
(min-y (apply min (map cadr fern)))
(max-y (apply max (map cadr fern)))
(scale-x (/ (- width 50) (- max-x min-x)))
(scale-y (/ (- height 50) (- max-y min-y)))
(scale-points (lambda (point)
(list (truncate (+ 20 (* scale-x (- (car point) min-x))))
(truncate (+ 20 (* scale-y (- (cadr point) min-y))))))))
(display
(string-append "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 "
(number->string width) " " (number->string height) "\n"))
;; add each point in fern as an arc - sets linewidth based on depth in tree
(for-each (lambda (point)
(display
(string-append (number->string (list-ref point 0))
" "
(number->string (list-ref point 1))
" 0.1 0 360 arc\nstroke\n")))
(map scale-points fern))
(display "\n%%EOF")))))
(output-fern-as-eps "barnsley.eps" (create-fern 0 0 50000)) |
http://rosettacode.org/wiki/Averages/Root_mean_square | Averages/Root mean square | Task[edit]
Compute the Root mean square of the numbers 1..10.
The root mean square is also known by its initials RMS (or rms), and as the quadratic mean.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
x
r
m
s
=
x
1
2
+
x
2
2
+
⋯
+
x
n
2
n
.
{\displaystyle x_{\mathrm {rms} }={\sqrt {{{x_{1}}^{2}+{x_{2}}^{2}+\cdots +{x_{n}}^{2}} \over n}}.}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Ursala | Ursala | #import nat
#import flo
#cast %e
rms = sqrt mean sqr* float* nrange(1,10) |
http://rosettacode.org/wiki/Averages/Root_mean_square | Averages/Root mean square | Task[edit]
Compute the Root mean square of the numbers 1..10.
The root mean square is also known by its initials RMS (or rms), and as the quadratic mean.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
x
r
m
s
=
x
1
2
+
x
2
2
+
⋯
+
x
n
2
n
.
{\displaystyle x_{\mathrm {rms} }={\sqrt {{{x_{1}}^{2}+{x_{2}}^{2}+\cdots +{x_{n}}^{2}} \over n}}.}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Vala | Vala | double rms(double[] list){
double sum_squares = 0;
double mean;
foreach ( double number in list){
sum_squares += (number * number);
}
mean = Math.sqrt(sum_squares / (double) list.length);
return mean;
} // end rms
public static void main(){
double[] list = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
double mean = rms(list);
stdout.printf("%s\n", mean.to_string());
} |
http://rosettacode.org/wiki/Babbage_problem | Babbage problem |
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
What is the smallest positive integer whose square ends in the digits 269,696?
— Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.
He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.
Task[edit]
The task is to find out if Babbage had the right answer — and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand.
As Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.
For these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].
Motivation
The aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.
| #Elixir | Elixir | defmodule Babbage do
def problem(n) when rem(n*n,1000000)==269696, do: n
def problem(n), do: problem(n+2)
end
IO.puts Babbage.problem(0) |
http://rosettacode.org/wiki/Averages/Simple_moving_average | Averages/Simple moving average | Computing the simple moving average of a series of numbers.
Task[edit]
Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far.
Description
A simple moving average is a method for computing an average of a stream of numbers by only averaging the last P numbers from the stream, where P is known as the period.
It can be implemented by calling an initialing routine with P as its argument, I(P), which should then return a routine that when called with individual, successive members of a stream of numbers, computes the mean of (up to), the last P of them, lets call this SMA().
The word stateful in the task description refers to the need for SMA() to remember certain information between calls to it:
The period, P
An ordered container of at least the last P numbers from each of its individual calls.
Stateful also means that successive calls to I(), the initializer, should return separate routines that do not share saved state so they could be used on two independent streams of data.
Pseudo-code for an implementation of SMA is:
function SMA(number: N):
stateful integer: P
stateful list: stream
number: average
stream.append_last(N)
if stream.length() > P:
# Only average the last P elements of the stream
stream.delete_first()
if stream.length() == 0:
average = 0
else:
average = sum( stream.values() ) / stream.length()
return average
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #J | J | 5 (+/%#)\ 1 2 3 4 5 5 4 3 2 1 NB. not a solution for this task
3 3.8 4.2 4.2 3.8 3 |
http://rosettacode.org/wiki/Averages/Pythagorean_means | Averages/Pythagorean means | Task[edit]
Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive).
Show that
A
(
x
1
,
…
,
x
n
)
≥
G
(
x
1
,
…
,
x
n
)
≥
H
(
x
1
,
…
,
x
n
)
{\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})}
for this set of positive integers.
The most common of the three means, the arithmetic mean, is the sum of the list divided by its length:
A
(
x
1
,
…
,
x
n
)
=
x
1
+
⋯
+
x
n
n
{\displaystyle A(x_{1},\ldots ,x_{n})={\frac {x_{1}+\cdots +x_{n}}{n}}}
The geometric mean is the
n
{\displaystyle n}
th root of the product of the list:
G
(
x
1
,
…
,
x
n
)
=
x
1
⋯
x
n
n
{\displaystyle G(x_{1},\ldots ,x_{n})={\sqrt[{n}]{x_{1}\cdots x_{n}}}}
The harmonic mean is
n
{\displaystyle n}
divided by the sum of the reciprocal of each item in the list:
H
(
x
1
,
…
,
x
n
)
=
n
1
x
1
+
⋯
+
1
x
n
{\displaystyle H(x_{1},\ldots ,x_{n})={\frac {n}{{\frac {1}{x_{1}}}+\cdots +{\frac {1}{x_{n}}}}}}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #ALGOL_68 | ALGOL 68 | main: (
INT count:=0;
LONG REAL f, sum:=0, prod:=1, resum:=0;
FORMAT real = $g(0,4)$; # preferred real format #
FILE fbuf; STRING sbuf; associate(fbuf,sbuf);
BOOL opts := TRUE;
FOR i TO argc DO
IF opts THEN # skip args up to the - token #
opts := argv(i) NE "-"
ELSE
rewind(fbuf); sbuf := argv(i); get(fbuf,f);
count +:= 1;
sum +:= f;
prod *:= f;
resum +:= 1/f
FI
OD;
printf(($"c: "f(real)l"s: "f(real)l"p: "f(real)l"r: "f(real)l$,count,sum,prod,resum));
printf(($"Arithmetic mean = "f(real)l$,sum/count));
printf(($"Geometric mean = "f(real)l$,prod**(1/count)));
printf(($"Harmonic mean = "f(real)l$,count/resum))
) |
http://rosettacode.org/wiki/Barnsley_fern | Barnsley fern |
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS).
Task
Create this fractal fern, using the following transformations:
ƒ1 (chosen 1% of the time)
xn + 1 = 0
yn + 1 = 0.16 yn
ƒ2 (chosen 85% of the time)
xn + 1 = 0.85 xn + 0.04 yn
yn + 1 = −0.04 xn + 0.85 yn + 1.6
ƒ3 (chosen 7% of the time)
xn + 1 = 0.2 xn − 0.26 yn
yn + 1 = 0.23 xn + 0.22 yn + 1.6
ƒ4 (chosen 7% of the time)
xn + 1 = −0.15 xn + 0.28 yn
yn + 1 = 0.26 xn + 0.24 yn + 0.44.
Starting position: x = 0, y = 0
| #Scilab | Scilab |
iteractions=1.0d6;
XY=zeros(2,iteractions+1);
x=0;
y=0;
i=2;
while i<iteractions+2
random_numbers=rand();
xp=x;
if random_numbers(1) < 0.01 then
x = 0;
y = 0.16 * y;
elseif random_numbers(1) >= 0.01 & random_numbers(1) < 0.01+0.85 then
x = 0.85 * x + 0.04 * y;
y = -0.04 * xp + 0.85 * y + 1.6;
elseif random_numbers(1) >= 0.86 & random_numbers(1) < 0.86+0.07 then
x = 0.2 * x - 0.26 * y;
y = 0.23 * xp + 0.22 * y + 1.6;
else
x = -0.15 * x + 0.28 * y;
y = 0.26 * xp + 0.24 * y + 0.44;
end
XY(1,i)=x;
XY(2,i)=y;
i=i+1;
end
scf(0);
clf();
xname('Barnsley fern');
plot2d(XY(1,:),XY(2,:),-0)
axes=gca();
axes.isoview="on";
axes.children.children.mark_foreground=13;
|
http://rosettacode.org/wiki/Barnsley_fern | Barnsley fern |
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS).
Task
Create this fractal fern, using the following transformations:
ƒ1 (chosen 1% of the time)
xn + 1 = 0
yn + 1 = 0.16 yn
ƒ2 (chosen 85% of the time)
xn + 1 = 0.85 xn + 0.04 yn
yn + 1 = −0.04 xn + 0.85 yn + 1.6
ƒ3 (chosen 7% of the time)
xn + 1 = 0.2 xn − 0.26 yn
yn + 1 = 0.23 xn + 0.22 yn + 1.6
ƒ4 (chosen 7% of the time)
xn + 1 = −0.15 xn + 0.28 yn
yn + 1 = 0.26 xn + 0.24 yn + 0.44.
Starting position: x = 0, y = 0
| #SequenceL | SequenceL | import <Utilities/Math.sl>;
import <Utilities/Random.sl>;
transform(p(1), rand) :=
let
x := p[1]; y := p[2];
in
[0.0, 0.16*y] when rand <= 0.01
else
[0.85*x + 0.04*y, -0.04*x + 0.85*y + 1.6] when rand <= 0.86
else
[0.2*x - 0.26*y, 0.23*x + 0.22*y + 1.6] when rand <= 0.93
else
[-0.15*x + 0.28*y, 0.26*x + 0.24*y + 0.44];
barnsleyFern(rand, count, result(2)) :=
let
nextRand := getRandom(rand);
next := transform(result[size(result)], nextRand.value / 2147483647.0);
in
result when count <= 0
else
barnsleyFern(nextRand.generator, count - 1, result ++ [next]);
scale(p(1), width, height) := [round((p[1] + 2.182) * width / 4.8378),
round((9.9983 - p[2]) * height / 9.9983)];
entry(seed, count, width, height) :=
let
fern := barnsleyFern(seedRandom(seed), count, [[0.0,0.0]]);
in
scale(fern, width, height); |
http://rosettacode.org/wiki/Averages/Root_mean_square | Averages/Root mean square | Task[edit]
Compute the Root mean square of the numbers 1..10.
The root mean square is also known by its initials RMS (or rms), and as the quadratic mean.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
x
r
m
s
=
x
1
2
+
x
2
2
+
⋯
+
x
n
2
n
.
{\displaystyle x_{\mathrm {rms} }={\sqrt {{{x_{1}}^{2}+{x_{2}}^{2}+\cdots +{x_{n}}^{2}} \over n}}.}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #VBA | VBA | Private Function root_mean_square(s() As Variant) As Double
For i = 1 To UBound(s)
s(i) = s(i) ^ 2
Next i
root_mean_square = Sqr(WorksheetFunction.sum(s) / UBound(s))
End Function
Public Sub pythagorean_means()
Dim s() As Variant
s = [{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}]
Debug.Print root_mean_square(s)
End Sub |
http://rosettacode.org/wiki/Averages/Root_mean_square | Averages/Root mean square | Task[edit]
Compute the Root mean square of the numbers 1..10.
The root mean square is also known by its initials RMS (or rms), and as the quadratic mean.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
x
r
m
s
=
x
1
2
+
x
2
2
+
⋯
+
x
n
2
n
.
{\displaystyle x_{\mathrm {rms} }={\sqrt {{{x_{1}}^{2}+{x_{2}}^{2}+\cdots +{x_{n}}^{2}} \over n}}.}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Vlang | Vlang | import math
fn main() {
n := 10
mut sum := 0.0
for x := 1.0; x <= n; x++ {
sum += x * x
}
println(math.sqrt(sum / n))
} |
http://rosettacode.org/wiki/Babbage_problem | Babbage problem |
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
What is the smallest positive integer whose square ends in the digits 269,696?
— Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.
He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.
Task[edit]
The task is to find out if Babbage had the right answer — and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand.
As Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.
For these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].
Motivation
The aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.
| #Erlang | Erlang |
-module(solution1).
-export([main/0]).
babbage(N,E) when N*N rem 1000000 == 269696 ->
io:fwrite("~p",[N]);
babbage(N,E) ->
case E of
4 -> babbage(N+2,6);
6 -> babbage(N+8,4)
end.
main()->
babbage(4,4).
|
http://rosettacode.org/wiki/Averages/Simple_moving_average | Averages/Simple moving average | Computing the simple moving average of a series of numbers.
Task[edit]
Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far.
Description
A simple moving average is a method for computing an average of a stream of numbers by only averaging the last P numbers from the stream, where P is known as the period.
It can be implemented by calling an initialing routine with P as its argument, I(P), which should then return a routine that when called with individual, successive members of a stream of numbers, computes the mean of (up to), the last P of them, lets call this SMA().
The word stateful in the task description refers to the need for SMA() to remember certain information between calls to it:
The period, P
An ordered container of at least the last P numbers from each of its individual calls.
Stateful also means that successive calls to I(), the initializer, should return separate routines that do not share saved state so they could be used on two independent streams of data.
Pseudo-code for an implementation of SMA is:
function SMA(number: N):
stateful integer: P
stateful list: stream
number: average
stream.append_last(N)
if stream.length() > P:
# Only average the last P elements of the stream
stream.delete_first()
if stream.length() == 0:
average = 0
else:
average = sum( stream.values() ) / stream.length()
return average
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Java | Java | import java.util.LinkedList;
import java.util.Queue;
public class MovingAverage {
private final Queue<Double> window = new LinkedList<Double>();
private final int period;
private double sum;
public MovingAverage(int period) {
assert period > 0 : "Period must be a positive integer";
this.period = period;
}
public void newNum(double num) {
sum += num;
window.add(num);
if (window.size() > period) {
sum -= window.remove();
}
}
public double getAvg() {
if (window.isEmpty()) return 0.0; // technically the average is undefined
return sum / window.size();
}
public static void main(String[] args) {
double[] testData = {1, 2, 3, 4, 5, 5, 4, 3, 2, 1};
int[] windowSizes = {3, 5};
for (int windSize : windowSizes) {
MovingAverage ma = new MovingAverage(windSize);
for (double x : testData) {
ma.newNum(x);
System.out.println("Next number = " + x + ", SMA = " + ma.getAvg());
}
System.out.println();
}
}
} |
http://rosettacode.org/wiki/Averages/Pythagorean_means | Averages/Pythagorean means | Task[edit]
Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive).
Show that
A
(
x
1
,
…
,
x
n
)
≥
G
(
x
1
,
…
,
x
n
)
≥
H
(
x
1
,
…
,
x
n
)
{\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})}
for this set of positive integers.
The most common of the three means, the arithmetic mean, is the sum of the list divided by its length:
A
(
x
1
,
…
,
x
n
)
=
x
1
+
⋯
+
x
n
n
{\displaystyle A(x_{1},\ldots ,x_{n})={\frac {x_{1}+\cdots +x_{n}}{n}}}
The geometric mean is the
n
{\displaystyle n}
th root of the product of the list:
G
(
x
1
,
…
,
x
n
)
=
x
1
⋯
x
n
n
{\displaystyle G(x_{1},\ldots ,x_{n})={\sqrt[{n}]{x_{1}\cdots x_{n}}}}
The harmonic mean is
n
{\displaystyle n}
divided by the sum of the reciprocal of each item in the list:
H
(
x
1
,
…
,
x
n
)
=
n
1
x
1
+
⋯
+
1
x
n
{\displaystyle H(x_{1},\ldots ,x_{n})={\frac {n}{{\frac {1}{x_{1}}}+\cdots +{\frac {1}{x_{n}}}}}}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #ALGOL_W | ALGOL W | begin
% returns the arithmetic mean of the elements of n from lo to hi %
real procedure arithmeticMean ( real array n ( * ); integer value lo, hi ) ;
begin
real sum;
sum := 0;
for i := lo until hi do sum := sum + n( i );
sum / ( 1 + ( hi - lo ) )
end arithmeticMean ;
% returns the geometric mean of the elements of n from lo to hi %
real procedure geometricMean ( real array n ( * ); integer value lo, hi ) ;
begin
real product;
product := 1;
for i := lo until hi do product := product * n( i );
exp( ln( product ) / ( 1 + ( hi - lo ) ) )
end geometricMean ;
% returns the harminic mean of the elements of n from lo to hi %
real procedure harmonicMean ( real array n ( * ); integer value lo, hi ) ;
begin
real sum;
sum := 0;
for i := lo until hi do sum := sum + ( 1 / n( i ) );
( 1 + ( hi - lo ) ) / sum
end harmonicMean ;
real array v ( 1 :: 10 );
for i := 1 until 10 do v( i ) := i;
r_w := 10; r_d := 5; r_format := "A"; s_w := 0; % set output format %
write( "Arithmetic mean: ", arithmeticMean( v, 1, 10 ) );
write( "Geometric mean: ", geometricMean( v, 1, 10 ) );
write( "Harmonic mean: ", harmonicMean( v, 1, 10 ) )
end. |
http://rosettacode.org/wiki/Barnsley_fern | Barnsley fern |
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS).
Task
Create this fractal fern, using the following transformations:
ƒ1 (chosen 1% of the time)
xn + 1 = 0
yn + 1 = 0.16 yn
ƒ2 (chosen 85% of the time)
xn + 1 = 0.85 xn + 0.04 yn
yn + 1 = −0.04 xn + 0.85 yn + 1.6
ƒ3 (chosen 7% of the time)
xn + 1 = 0.2 xn − 0.26 yn
yn + 1 = 0.23 xn + 0.22 yn + 1.6
ƒ4 (chosen 7% of the time)
xn + 1 = −0.15 xn + 0.28 yn
yn + 1 = 0.26 xn + 0.24 yn + 0.44.
Starting position: x = 0, y = 0
| #Sidef | Sidef | require('Imager')
var w = 640
var h = 640
var img = %O<Imager>.new(xsize => w, ysize => h, channels => 3)
var green = %O<Imager::Color>.new('#00FF00')
var (x, y) = (0.float, 0.float)
1e5.times {
var r = 100.rand
(x, y) = (
if (r <= 1) { ( 0.00*x - 0.00*y, 0.00*x + 0.16*y + 0.00) }
elsif (r <= 8) { ( 0.20*x - 0.26*y, 0.23*x + 0.22*y + 1.60) }
elsif (r <= 15) { (-0.15*x + 0.28*y, 0.26*x + 0.24*y + 0.44) }
else { ( 0.85*x + 0.04*y, -0.04*x + 0.85*y + 1.60) }
)
img.setpixel(x => w/2 + 60*x, y => 60*y, color => green)
}
img.flip(dir => 'v')
img.write(file => 'barnsleyFern.png') |
http://rosettacode.org/wiki/Averages/Root_mean_square | Averages/Root mean square | Task[edit]
Compute the Root mean square of the numbers 1..10.
The root mean square is also known by its initials RMS (or rms), and as the quadratic mean.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
x
r
m
s
=
x
1
2
+
x
2
2
+
⋯
+
x
n
2
n
.
{\displaystyle x_{\mathrm {rms} }={\sqrt {{{x_{1}}^{2}+{x_{2}}^{2}+\cdots +{x_{n}}^{2}} \over n}}.}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Wortel | Wortel | @let {
; using a composition and a fork (like you would do in J)
rms1 ^(@sqrt @(@sum / #) *^@sq)
; using a function with a named argument
rms2 &a @sqrt ~/ #a @sum !*^@sq a
[[
!rms1 @to 10
!rms2 @to 10
]]
} |
http://rosettacode.org/wiki/Averages/Root_mean_square | Averages/Root mean square | Task[edit]
Compute the Root mean square of the numbers 1..10.
The root mean square is also known by its initials RMS (or rms), and as the quadratic mean.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
x
r
m
s
=
x
1
2
+
x
2
2
+
⋯
+
x
n
2
n
.
{\displaystyle x_{\mathrm {rms} }={\sqrt {{{x_{1}}^{2}+{x_{2}}^{2}+\cdots +{x_{n}}^{2}} \over n}}.}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Wren | Wren | var rms = ((1..10).reduce(0) { |acc, i| acc + i*i }/10).sqrt
System.print(rms) |
http://rosettacode.org/wiki/Babbage_problem | Babbage problem |
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
What is the smallest positive integer whose square ends in the digits 269,696?
— Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.
He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.
Task[edit]
The task is to find out if Babbage had the right answer — and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand.
As Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.
For these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].
Motivation
The aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.
| #F.23 | F# |
let mutable n=1
while(((n*n)%( 1000000 ))<> 269696) do
n<-n+1
printf"%i"n
|
http://rosettacode.org/wiki/Babbage_problem | Babbage problem |
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
What is the smallest positive integer whose square ends in the digits 269,696?
— Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.
He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.
Task[edit]
The task is to find out if Babbage had the right answer — and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand.
As Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.
For these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].
Motivation
The aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.
| #Factor | Factor | ! Lines like this one are comments. They are meant for humans to
! read and have no effect on the instructions carried out by the
! computer (aside from Factor's parser ignoring them).
! Comments may appear after program instructions on the same
! line.
! Each word between USING: and ; is a vocabulary. By importing
! a vocabulary in this way, its words are made available for the
! program to use. This is a way to keep the space requirements
! down for deployed programs, and a nice side effect is that it
! gives readers a clue for where to look for documentation.
USING: kernel math math.ranges prettyprint sequences ;
! Before the program begins, it's incredibly helpful to have an
! understanding of Factor's dataflow model. Don't worry; it's
! not complicated, but it's confusing to read a Factor program
! without this knowledge.
! Factor is a stack-based language. What this means is that
! there is an implicit data stack in the background, waiting
! to recieve whatever manner of thing we wish to give it. Here
! is a simple arithmetic expression to demonstrate:
! language token | data stack
! ---------------+-----------
! 2 2 ! numbers place themselves on the stack.
! 1 2 1
! 4 2 1 4
! + 2 5 ! consume 1 and 4 and leave behind 5.
! * 10 ! consume 2 and 5 and leave behind 10.
! Thus the phrase
! 2 1 4 + *
! in Factor is a way to calculate 2 * (4 + 1).
! We could have also written this as
! 1 4 + 2 *
! with no change in meaning or outcome.
! Because of the way the data stack works, there is no need
! to specify order of operations in the language, because you do
! so inherently by the order you place things on the data stack.
! === BEGIN PROGRAM ============================================
518 99,736 2 <range> ! Here we place three numbers on the
! stack representing a range of numbers.
! The first, 518, represents the starting
! point of the sequence. 99,736
! represents the ending point of the
! sequence. 2 represents the "step" of
! the sequence, or a constant distance
! between members.
! <range> takes those three numbers and
! creates an object representing the
! described range of numbers. Computers
! of today are more than capable of
! storing that many numbers, but <range>
! doesn't store them all; it calculates
! the number that is needed at the
! current time.
! The rationale for the sequence is as
! follows. Odd squares are always odd, so
! we don't need to consider them. That's
! why the sequence starts with an even
! number and is incremented by 2. We
! choose 518 to start because it's the
! largest even square less than 269,696.
! We choose 99,736 to end because we
! know it's a solution.
[ sq 1,000,000 mod 269,696 = ]
! the [ ... ] form is called a quotation.
! Think of it like a sequence that stores
! code. It's a way to place code on the
! data stack without executing it. This
! is so that it can be used by the find
! word. You could also think of it much
! like a function that hasn't been given
! a name.
find
! When we call the find word, there are
! two objects on the stack: a sequence
! and a quotation. find is a word that
! takes a sequence and a quotation and
! applies the quotation to one member of
! the sequence after another. It does
! so until the quotation returns a t
! value (denoting a boolean true) and
! then leaves that number, along with its
! index in the sequence, on the stack.
! Let's take a look at what happens
! for each iteration of find. Let's look
! at what happens with the first number
! in the sequence.
! language token | data stack
! ---------------+-----------
! 518 518 ! 518 is placed on the stack
! from the sequence by find.
! sq 268,324 ! square it
! 1,000,000 268,324 1,000,000 ! place a million on the stack
! mod 268,324 ! take modulus of 268,324
! and 1,000,000
! 269,696 268,324 269,696 ! place 269,696 on the stack
! = f ! test 268,324 and 269,696 for
! equality.
! So the square of the first number in
! the sequence, 518, does not end with
! 269,696. We'll try each number in the
! sequence until we get a t.
. ! Consume the top member of the data stack and print it out.
drop ! find leaves both the found element from the sequence
! and the index at which it was found on the data stack.
! We don't care about the index so we will call drop to
! remove it from the top of the data stack. All programs
! must end with an emtpy data stack.
! Putting the entire program together, it looks like this:
! 518 99,736 2 <range> [ sq 1,000,000 mod 269,696 = ] find . drop |
http://rosettacode.org/wiki/Averages/Mode | Averages/Mode | Task[edit]
Write a program to find the mode value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriate or possible to support an unspecified value type, use integers.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #11l | 11l | F modes(values)
DefaultDict[Int, Int] count
L(v) values
count[v]++
V best = max(count.values())
R count.filter(kv -> kv[1] == @best).map(kv -> kv[0])
print(modes([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17]))
print(modes([1, 1, 2, 4, 4])) |
http://rosettacode.org/wiki/Averages/Simple_moving_average | Averages/Simple moving average | Computing the simple moving average of a series of numbers.
Task[edit]
Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far.
Description
A simple moving average is a method for computing an average of a stream of numbers by only averaging the last P numbers from the stream, where P is known as the period.
It can be implemented by calling an initialing routine with P as its argument, I(P), which should then return a routine that when called with individual, successive members of a stream of numbers, computes the mean of (up to), the last P of them, lets call this SMA().
The word stateful in the task description refers to the need for SMA() to remember certain information between calls to it:
The period, P
An ordered container of at least the last P numbers from each of its individual calls.
Stateful also means that successive calls to I(), the initializer, should return separate routines that do not share saved state so they could be used on two independent streams of data.
Pseudo-code for an implementation of SMA is:
function SMA(number: N):
stateful integer: P
stateful list: stream
number: average
stream.append_last(N)
if stream.length() > P:
# Only average the last P elements of the stream
stream.delete_first()
if stream.length() == 0:
average = 0
else:
average = sum( stream.values() ) / stream.length()
return average
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #JavaScript | JavaScript | function simple_moving_averager(period) {
var nums = [];
return function(num) {
nums.push(num);
if (nums.length > period)
nums.splice(0,1); // remove the first element of the array
var sum = 0;
for (var i in nums)
sum += nums[i];
var n = period;
if (nums.length < period)
n = nums.length;
return(sum/n);
}
}
var sma3 = simple_moving_averager(3);
var sma5 = simple_moving_averager(5);
var data = [1,2,3,4,5,5,4,3,2,1];
for (var i in data) {
var n = data[i];
// using WSH
WScript.Echo("Next number = " + n + ", SMA_3 = " + sma3(n) + ", SMA_5 = " + sma5(n));
} |
http://rosettacode.org/wiki/Averages/Pythagorean_means | Averages/Pythagorean means | Task[edit]
Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive).
Show that
A
(
x
1
,
…
,
x
n
)
≥
G
(
x
1
,
…
,
x
n
)
≥
H
(
x
1
,
…
,
x
n
)
{\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})}
for this set of positive integers.
The most common of the three means, the arithmetic mean, is the sum of the list divided by its length:
A
(
x
1
,
…
,
x
n
)
=
x
1
+
⋯
+
x
n
n
{\displaystyle A(x_{1},\ldots ,x_{n})={\frac {x_{1}+\cdots +x_{n}}{n}}}
The geometric mean is the
n
{\displaystyle n}
th root of the product of the list:
G
(
x
1
,
…
,
x
n
)
=
x
1
⋯
x
n
n
{\displaystyle G(x_{1},\ldots ,x_{n})={\sqrt[{n}]{x_{1}\cdots x_{n}}}}
The harmonic mean is
n
{\displaystyle n}
divided by the sum of the reciprocal of each item in the list:
H
(
x
1
,
…
,
x
n
)
=
n
1
x
1
+
⋯
+
1
x
n
{\displaystyle H(x_{1},\ldots ,x_{n})={\frac {n}{{\frac {1}{x_{1}}}+\cdots +{\frac {1}{x_{n}}}}}}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Amazing_Hopper | Amazing Hopper |
#include <hopper.h>
/* An example of definitions in pseudo-natural language, with synonimous.
These definitions can be inside a definition file (xxxx.h) */
#define getasinglelistof(_X_) {_X_},
#synon getasinglelistof getalistof
#define integerrandomnumbers _V1000_=-1,rand array(_V1000_),mulby(10),ceil,
#define randomnumbers _V1000_=-1,rand array(_V1000_)
#define rememberitin(_X_) _X_=0,cpy(_X_)
#synon rememberitin rememberthisnumbersin
#define rememberas(_X_) mov(_X_)
#define remember(_X_) {_X_}
//#synon remember with ---> this exist in HOPPER.H
#defn nowconsiderthis(_X_) #ATOM#CMPLX,print
#synon nowconsiderthis nowconsider,considerthis,consider,nowputtext,puttext,andprint
#define andprintwithanewline {"\n"}print
#synon andprintwithanewline printwithanewline
//#defn andprint(_X_) #ATOM#CMPLX,print
#define putanewline {"\n"}
#define withanewline "\n"
#define andprintit print
#synon andprintit printit,andprint
#define showit show
#define afterdoingit emptystack?,not,do{ {"I cannot continue due to retentive data "},throw(1001) }
#synon afterdoingit secondly,finally
#define then emptystack?do{ {"I cannot continue because data is missing "},throw(1000) }
/* why "#context" and not "#define"?
becose "#context" need a value in the stack for continue.
Internally, "domeanit" tranform to "gosub(calculatearithmeticmean)",
and "gosub" works only if it finds a data in the stack */
#context calculatethegeometricmean
#synon calculatethegeometricmean calculategeometricmean,getgeometricmean
#context calculatetheharmonicmean
#synon calculatetheharmonicmean calculateharmonicmean,getharmonicmean
#context calculatearitmethicmean
#synon calculatearitmethicmean calculatesinglemean,calculatemean,domeanit
main:
consider this ("Arithmetic Mean: ")
get a list of '10,10' integer random numbers; remember this numbers in 'list of numbers';
then, do mean it, and print with a new line.
after doing it, consider ("Geometric Mean: "), remember 'list of numbers', calculate the geometric mean;
then, put a new line, and print it.
/*
Okay. This can be a bit long, if we have to write the program;
But what if we just had to talk, and the language interpreter takes care of the rest?
*/
secondly, now consider ("Harmonic Mean: "), with 'list of numbers', get harmonic mean, and print with a new line.
finally, put text ("Original Array:\n"), and print (list of numbers, with a new line)
exit(0)
.locals
calculate aritmethic mean:
stats(MEAN)
back
calculate the geometric mean:
stats(GEOMEAN)
back
calculatetheharmonicmean:
stats(HARMEAN)
back
|
http://rosettacode.org/wiki/Barnsley_fern | Barnsley fern |
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS).
Task
Create this fractal fern, using the following transformations:
ƒ1 (chosen 1% of the time)
xn + 1 = 0
yn + 1 = 0.16 yn
ƒ2 (chosen 85% of the time)
xn + 1 = 0.85 xn + 0.04 yn
yn + 1 = −0.04 xn + 0.85 yn + 1.6
ƒ3 (chosen 7% of the time)
xn + 1 = 0.2 xn − 0.26 yn
yn + 1 = 0.23 xn + 0.22 yn + 1.6
ƒ4 (chosen 7% of the time)
xn + 1 = −0.15 xn + 0.28 yn
yn + 1 = 0.26 xn + 0.24 yn + 0.44.
Starting position: x = 0, y = 0
| #SPL | SPL | w,h = #.scrsize()
x,y = 0
>
r = #.rnd(100)
? r<85, x,y = f2(x,y)
? r!<85 & r<92, x,y = f3(x,y)
? r!<92 & r<99, x,y = f4(x,y)
? r!<99, x,y = f1(y)
#.drawpoint(x/10*w+w/2,h-y/10*h,0,0.5,0,0.1)
<
f1(y) <= 0, 0.16*y
f2(x,y) <= 0.85*x+0.04*y, -0.04*x+0.85*y+1.6
f3(x,y) <= 0.2*x-0.26*y, 0.23*x+0.22*y+1.6
f4(x,y) <= -0.15*x+0.28*y, 0.26*x+0.24*y+0.44 |
http://rosettacode.org/wiki/Barnsley_fern | Barnsley fern |
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS).
Task
Create this fractal fern, using the following transformations:
ƒ1 (chosen 1% of the time)
xn + 1 = 0
yn + 1 = 0.16 yn
ƒ2 (chosen 85% of the time)
xn + 1 = 0.85 xn + 0.04 yn
yn + 1 = −0.04 xn + 0.85 yn + 1.6
ƒ3 (chosen 7% of the time)
xn + 1 = 0.2 xn − 0.26 yn
yn + 1 = 0.23 xn + 0.22 yn + 1.6
ƒ4 (chosen 7% of the time)
xn + 1 = −0.15 xn + 0.28 yn
yn + 1 = 0.26 xn + 0.24 yn + 0.44.
Starting position: x = 0, y = 0
| #Standard_ML | Standard ML | open XWindows ;
open Motif ;
val uniformdeviate = fn seed =>
let
val in31m = (Real.fromInt o Int32.toInt ) (getOpt (Int32.maxInt,0) );
val in31 = in31m +1.0;
val (s1,s2,v) = (41160.0 , 950665216.0 , Real.realFloor seed);
val (val1,val2) = (v*s1, v*s2);
val next1 = Real.fromLargeInt (Real.toLargeInt IEEEReal.TO_NEGINF (val1/in31)) ;
val next2 = Real.rem(Real.realFloor(val2/in31) , in31m );
val valt = val1+val2 - (next1+next2)*in31m;
val nextt = Real.realFloor(valt/in31m);
val valt = valt - nextt*in31m;
in
(valt/in31m,valt)
end;
local
val sizeup = 60.0 ;
fun toI {x=x,y=y} = {x=Real.toInt IEEEReal.TO_NEAREST (sizeup *x),y=Real.toInt IEEEReal.TO_NEAREST (sizeup*y)} ;
val next = [ (fn {x=x,y=y} => {x= 0.0, y= 0.16*y })
, (fn {x=x,y=y} => {x= 0.85*x+0.04*y, y= ~0.04*x+0.85*y+1.6})
, (fn {x=x,y=y} => {x= 0.2*x-0.26*y, y= 0.23*x+0.22*y+1.6 })
, (fn {x=x,y=y} => {x= ~0.15*x+0.28*y,y= 0.26*x+0.24*y+0.44}) ] ;
val seed = ref 100027.0
in
fun putNext 1 win usegc coord = XFlush (XtDisplay win)
| putNext N win usegc coord =
let
val (i,ns) = uniformdeviate ( !seed ) ;
val _ = seed := ns ;
val fi = List.nth (next, List.foldr (fn (a,b) => b + (if i>a then 1 else 0)) 0 [0.1,0.86,0.93,1.0] ) ;
val nwp = fi coord
in
(XDrawPoint (XtWindow win) usegc ( AddPoint ((XPoint o toI) coord, XPoint {x=300,y=0}) ) ;
putNext (N-1) win usegc nwp )
end
end;
val demoWindow = fn () =>
let
val shell = XtAppInitialise "" "demo" "top" [] [ XmNwidth 600, XmNheight 700 ] ;
val main = XmCreateMainWindow shell "main" [ XmNmappedWhenManaged true ] ;
val canvas = XmCreateDrawingArea main "drawarea" [ XmNwidth 600, XmNheight 700] ;
val usegc = DefaultGC (XtDisplay canvas) ;
val _ = XSetForeground usegc 0x4a632d ;
val drawall = fn (w,c,t)=> ( XClearWindow (XtWindow canvas ); putNext 1000000 canvas usegc {x=0.0,y=0.0} ; t )
in
(
XtSetCallbacks canvas [ (XmNexposeCallback , drawall) ] XmNarmCallback ;
XtManageChild canvas ;
XtManageChild main ;
XtRealizeWidget shell
)
end ; |
http://rosettacode.org/wiki/Averages/Root_mean_square | Averages/Root mean square | Task[edit]
Compute the Root mean square of the numbers 1..10.
The root mean square is also known by its initials RMS (or rms), and as the quadratic mean.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
x
r
m
s
=
x
1
2
+
x
2
2
+
⋯
+
x
n
2
n
.
{\displaystyle x_{\mathrm {rms} }={\sqrt {{{x_{1}}^{2}+{x_{2}}^{2}+\cdots +{x_{n}}^{2}} \over n}}.}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #XLISP | XLISP | (defun quadratic-mean (xs)
(sqrt
(/
(apply +
(mapcar (lambda (x) (expt x 2)) xs))
(length xs))))
; define a RANGE function, for testing purposes
(defun range (x y)
(if (< x y)
(cons x (range (+ x 1) y))))
; test QUADRATIC-MEAN
(print (quadratic-mean (range 1 11))) |
http://rosettacode.org/wiki/Averages/Root_mean_square | Averages/Root mean square | Task[edit]
Compute the Root mean square of the numbers 1..10.
The root mean square is also known by its initials RMS (or rms), and as the quadratic mean.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
x
r
m
s
=
x
1
2
+
x
2
2
+
⋯
+
x
n
2
n
.
{\displaystyle x_{\mathrm {rms} }={\sqrt {{{x_{1}}^{2}+{x_{2}}^{2}+\cdots +{x_{n}}^{2}} \over n}}.}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #XPL0 | XPL0 | code CrLf=9;
code real RlOut=48;
int N;
real S;
[S:= 0.0;
for N:= 1 to 10 do S:= S + sq(float(N));
RlOut(0, sqrt(S/10.0));
CrLf(0);
] |
http://rosettacode.org/wiki/Babbage_problem | Babbage problem |
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
What is the smallest positive integer whose square ends in the digits 269,696?
— Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.
He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.
Task[edit]
The task is to find out if Babbage had the right answer — and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand.
As Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.
For these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].
Motivation
The aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.
| #Forth | Forth | ( First we set out the steps the computer will use to solve the problem )
: BABBAGE
1 ( start from the number 1 )
BEGIN ( commence a "loop": the computer will return to this point repeatedly )
1+ ( add 1 to our number )
DUP DUP ( duplicate the result twice, so we now have three copies )
( We need three because we are about to multiply two of them together to find the square, and the third will be used the next time we go around the loop -- unless we have found our answer, in which case we shall need to print it out )
* ( * means "multiply", so we now have the square )
1000000 MOD ( find the remainder after dividing it by a million )
269696 = ( is it equal to 269,696? )
UNTIL ( keep repeating the steps from BEGIN until the condition is satisfied )
. ; ( when it is satisfied, print out the number that allowed us to satisfy it )
( Now we ask the machine to carry out these instructions )
BABBAGE |
http://rosettacode.org/wiki/Averages/Mode | Averages/Mode | Task[edit]
Write a program to find the mode value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriate or possible to support an unspecified value type, use integers.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Action.21 | Action! | DEFINE MAX="100"
INT ARRAY keys(MAX)
INT ARRAY values(MAX)
BYTE count
PROC PrintArray(INT ARRAY a INT size)
INT i
Put('[)
FOR i=0 TO size-1
DO
IF i>0 THEN Put(' ) FI
PrintI(a(i))
OD
Put(']) PutE()
RETURN
PROC ClearMap()
count=0
RETURN
PROC AddToMap(INT a)
INT i,index
index=-1
IF count>0 THEN
FOR i=0 TO count-1
DO
IF keys(i)=a THEN
index=i EXIT
FI
OD
FI
IF index=-1 THEN
keys(count)=a
values(count)=1
count==+1
ELSE
values(index)==+1
FI
RETURN
PROC Mode(INT ARRAY a INT aSize INT ARRAY m INT POINTER mSize)
INT i,mx
ClearMap()
FOR i=0 TO aSize-1
DO
AddToMap(a(i))
OD
mx=0
FOR i=0 TO count-1
DO
IF values(i)>mx THEN
mx=values(i)
FI
OD
mSize^=0
FOR i=0 TO count-1
DO
IF values(i)=mx THEN
m(mSize^)=keys(i)
mSize^==+1
FI
OD
RETURN
PROC Test(INT ARRAY a INT size)
INT ARRAY m(MAX)
INT mSize
PrintE("Array:") PrintArray(a,size)
Mode(a,size,m,@mSize)
PrintE("Mode:") PrintArray(m,mSize)
PutE()
RETURN
PROC Main()
INT ARRAY a=[1 3 5 7 3 1 3 7 7 3 3]
INT ARRAY b=[7 13 5 13 7 2 7 10 13]
INT ARRAY c=[5]
Test(a,11)
Test(b,9)
Test(c,1)
RETURN |
http://rosettacode.org/wiki/Averages/Mode | Averages/Mode | Task[edit]
Write a program to find the mode value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriate or possible to support an unspecified value type, use integers.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #ActionScript | ActionScript | function Mode(arr:Array):Array {
//Create an associative array to count how many times each element occurs,
//an array to contain the modes, and a variable to store how many times each mode appears.
var count:Array = new Array();
var modeList:Array;
var maxCount:uint=0;
for (var i:String in arr) {
//Record how many times an element has occurred. Note that each element in the cuont array
//has to be initialized explicitly, since it is an associative array.
if (count[arr[i]]==undefined) {
count[arr[i]]=1;
} else {
count[arr[i]]++;
}
//If this is now the most common element, clear the list of modes, and add this element.
if(count[arr[i]] > maxCount)
{
maxCount=count[arr[i]];
modeList = new Array();
modeList.push(arr[i]);
}
//If this is a mode, add it to the list.
else if(count[arr[i]] == maxCount){
modeList.push(arr[i]);
}
}
return modeList;
} |
http://rosettacode.org/wiki/Averages/Simple_moving_average | Averages/Simple moving average | Computing the simple moving average of a series of numbers.
Task[edit]
Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far.
Description
A simple moving average is a method for computing an average of a stream of numbers by only averaging the last P numbers from the stream, where P is known as the period.
It can be implemented by calling an initialing routine with P as its argument, I(P), which should then return a routine that when called with individual, successive members of a stream of numbers, computes the mean of (up to), the last P of them, lets call this SMA().
The word stateful in the task description refers to the need for SMA() to remember certain information between calls to it:
The period, P
An ordered container of at least the last P numbers from each of its individual calls.
Stateful also means that successive calls to I(), the initializer, should return separate routines that do not share saved state so they could be used on two independent streams of data.
Pseudo-code for an implementation of SMA is:
function SMA(number: N):
stateful integer: P
stateful list: stream
number: average
stream.append_last(N)
if stream.length() > P:
# Only average the last P elements of the stream
stream.delete_first()
if stream.length() == 0:
average = 0
else:
average = sum( stream.values() ) / stream.length()
return average
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Julia | Julia | using Statistics |
http://rosettacode.org/wiki/Averages/Pythagorean_means | Averages/Pythagorean means | Task[edit]
Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive).
Show that
A
(
x
1
,
…
,
x
n
)
≥
G
(
x
1
,
…
,
x
n
)
≥
H
(
x
1
,
…
,
x
n
)
{\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})}
for this set of positive integers.
The most common of the three means, the arithmetic mean, is the sum of the list divided by its length:
A
(
x
1
,
…
,
x
n
)
=
x
1
+
⋯
+
x
n
n
{\displaystyle A(x_{1},\ldots ,x_{n})={\frac {x_{1}+\cdots +x_{n}}{n}}}
The geometric mean is the
n
{\displaystyle n}
th root of the product of the list:
G
(
x
1
,
…
,
x
n
)
=
x
1
⋯
x
n
n
{\displaystyle G(x_{1},\ldots ,x_{n})={\sqrt[{n}]{x_{1}\cdots x_{n}}}}
The harmonic mean is
n
{\displaystyle n}
divided by the sum of the reciprocal of each item in the list:
H
(
x
1
,
…
,
x
n
)
=
n
1
x
1
+
⋯
+
1
x
n
{\displaystyle H(x_{1},\ldots ,x_{n})={\frac {n}{{\frac {1}{x_{1}}}+\cdots +{\frac {1}{x_{n}}}}}}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #APL | APL |
arithmetic←{(+/⍵)÷⍴⍵}
geometric←{(×/⍵)*÷⍴⍵}
harmonic←{(⍴⍵)÷(+/÷⍵)}
x←⍳10
arithmetic x
5.5
geometric x
4.528728688
harmonic x
3.414171521 |
http://rosettacode.org/wiki/Barnsley_fern | Barnsley fern |
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS).
Task
Create this fractal fern, using the following transformations:
ƒ1 (chosen 1% of the time)
xn + 1 = 0
yn + 1 = 0.16 yn
ƒ2 (chosen 85% of the time)
xn + 1 = 0.85 xn + 0.04 yn
yn + 1 = −0.04 xn + 0.85 yn + 1.6
ƒ3 (chosen 7% of the time)
xn + 1 = 0.2 xn − 0.26 yn
yn + 1 = 0.23 xn + 0.22 yn + 1.6
ƒ4 (chosen 7% of the time)
xn + 1 = −0.15 xn + 0.28 yn
yn + 1 = 0.26 xn + 0.24 yn + 0.44.
Starting position: x = 0, y = 0
| #Swift | Swift | import UIKit
import CoreImage
import PlaygroundSupport
let imageWH = 300
let context = CGContext(data: nil,
width: imageWH,
height: imageWH,
bitsPerComponent: 8,
bytesPerRow: 0,
space: CGColorSpace(name: CGColorSpace.sRGB)!,
bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue)!
var x0 = 0.0
var x1 = 0.0
var y0 = 0.0
var y1 = 0.0
context.setFillColor(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1))
context.fill(CGRect(x: 0, y: 0, width: imageWH, height: imageWH))
context.setFillColor(#colorLiteral(red: 0.539716677, green: 1, blue: 0.265400682, alpha: 1))
for _ in 0..<100_000 {
switch Int(arc4random()) % 100 {
case 0:
x1 = 0
y1 = 0.16 * y0
case 1...7:
x1 = -0.15 * x0 + 0.28 * y0
y1 = 0.26 * x0 + 0.24 * y0 + 0.44
case 8...15:
x1 = 0.2 * x0 - 0.26 * y0
y1 = 0.23 * x0 + 0.22 * y0 + 1.6
default:
x1 = 0.85 * x0 + 0.04 * y0
y1 = -0.04 * x0 + 0.85 * y0 + 1.6
}
context.fill(CGRect(x: 30 * x1 + Double(imageWH) / 2.0, y: 30 * y1,
width: 1, height: 1))
(x0, y0) = (x1, y1)
}
let uiImage = UIImage(cgImage: context.makeImage()!) |
http://rosettacode.org/wiki/Barnsley_fern | Barnsley fern |
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS).
Task
Create this fractal fern, using the following transformations:
ƒ1 (chosen 1% of the time)
xn + 1 = 0
yn + 1 = 0.16 yn
ƒ2 (chosen 85% of the time)
xn + 1 = 0.85 xn + 0.04 yn
yn + 1 = −0.04 xn + 0.85 yn + 1.6
ƒ3 (chosen 7% of the time)
xn + 1 = 0.2 xn − 0.26 yn
yn + 1 = 0.23 xn + 0.22 yn + 1.6
ƒ4 (chosen 7% of the time)
xn + 1 = −0.15 xn + 0.28 yn
yn + 1 = 0.26 xn + 0.24 yn + 0.44.
Starting position: x = 0, y = 0
| #TI-83_BASIC | TI-83 BASIC | ClrDraw
Input "ITERS:",M
[[0,0,1]]→[A]
[[0,0,0][0,.16,0][0,0,1]]→[B]
[[.85,-.04,0][.04,.85,0][0,1.6,1]]→[C]
[[.2,.23,0][-.26,.22,0][0,1.6,1]]→[D]
[[-.15,.26,0][.28,.24,0][0,.44,1]]→[E]
0→I
While I<M
randInt(1,100)→R
If R=1
Then
[A][B]→[A]
101→R
End
If R<86
Then
[A][C]→[A]
101→R
End
If R<93
Then
[A][D]→[A]
101→R
End
If R<101:Then
[A][E]→[A]
End
round([A](1,1)*8+31,0)→E
round([A](1,2)*8,0)→F
Pxl-On(E,F)
I+1→I
End |
http://rosettacode.org/wiki/Averages/Root_mean_square | Averages/Root mean square | Task[edit]
Compute the Root mean square of the numbers 1..10.
The root mean square is also known by its initials RMS (or rms), and as the quadratic mean.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
x
r
m
s
=
x
1
2
+
x
2
2
+
⋯
+
x
n
2
n
.
{\displaystyle x_{\mathrm {rms} }={\sqrt {{{x_{1}}^{2}+{x_{2}}^{2}+\cdots +{x_{n}}^{2}} \over n}}.}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Yacas | Yacas | Sqrt(Add((1 .. 10)^2)/10) |
http://rosettacode.org/wiki/Averages/Root_mean_square | Averages/Root mean square | Task[edit]
Compute the Root mean square of the numbers 1..10.
The root mean square is also known by its initials RMS (or rms), and as the quadratic mean.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
x
r
m
s
=
x
1
2
+
x
2
2
+
⋯
+
x
n
2
n
.
{\displaystyle x_{\mathrm {rms} }={\sqrt {{{x_{1}}^{2}+{x_{2}}^{2}+\cdots +{x_{n}}^{2}} \over n}}.}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #zkl | zkl | fcn rms(z){ ( z.reduce(fcn(p,n){ p + n*n },0.0) /z.len() ).sqrt() } |
http://rosettacode.org/wiki/Babbage_problem | Babbage problem |
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
What is the smallest positive integer whose square ends in the digits 269,696?
— Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.
He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.
Task[edit]
The task is to find out if Babbage had the right answer — and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand.
As Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.
For these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].
Motivation
The aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.
| #Fortran | Fortran | DO 3 N=1,99736
IF(MODF(N*N,1000000)-269696)3,4,3
3 CONTINUE
4 PRINT 5,N
5 FORMAT(I6)
STOP
|
http://rosettacode.org/wiki/Averages/Mode | Averages/Mode | Task[edit]
Write a program to find the mode value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriate or possible to support an unspecified value type, use integers.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Ada | Ada | generic
type Element_Type is private;
type Element_Array is array (Positive range <>) of Element_Type;
package Mode is
function Get_Mode (Set : Element_Array) return Element_Array;
end Mode; |
http://rosettacode.org/wiki/Averages/Simple_moving_average | Averages/Simple moving average | Computing the simple moving average of a series of numbers.
Task[edit]
Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far.
Description
A simple moving average is a method for computing an average of a stream of numbers by only averaging the last P numbers from the stream, where P is known as the period.
It can be implemented by calling an initialing routine with P as its argument, I(P), which should then return a routine that when called with individual, successive members of a stream of numbers, computes the mean of (up to), the last P of them, lets call this SMA().
The word stateful in the task description refers to the need for SMA() to remember certain information between calls to it:
The period, P
An ordered container of at least the last P numbers from each of its individual calls.
Stateful also means that successive calls to I(), the initializer, should return separate routines that do not share saved state so they could be used on two independent streams of data.
Pseudo-code for an implementation of SMA is:
function SMA(number: N):
stateful integer: P
stateful list: stream
number: average
stream.append_last(N)
if stream.length() > P:
# Only average the last P elements of the stream
stream.delete_first()
if stream.length() == 0:
average = 0
else:
average = sum( stream.values() ) / stream.length()
return average
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #K | K |
v:v,|v:1+!5
v
1 2 3 4 5 5 4 3 2 1
avg:{(+/x)%#x}
sma:{avg'x@(,\!y),(1+!y)+\:!y}
sma[v;5]
1 1.5 2 2.5 3 3.8 4.2 4.2 3.8 3
|
http://rosettacode.org/wiki/Averages/Pythagorean_means | Averages/Pythagorean means | Task[edit]
Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive).
Show that
A
(
x
1
,
…
,
x
n
)
≥
G
(
x
1
,
…
,
x
n
)
≥
H
(
x
1
,
…
,
x
n
)
{\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})}
for this set of positive integers.
The most common of the three means, the arithmetic mean, is the sum of the list divided by its length:
A
(
x
1
,
…
,
x
n
)
=
x
1
+
⋯
+
x
n
n
{\displaystyle A(x_{1},\ldots ,x_{n})={\frac {x_{1}+\cdots +x_{n}}{n}}}
The geometric mean is the
n
{\displaystyle n}
th root of the product of the list:
G
(
x
1
,
…
,
x
n
)
=
x
1
⋯
x
n
n
{\displaystyle G(x_{1},\ldots ,x_{n})={\sqrt[{n}]{x_{1}\cdots x_{n}}}}
The harmonic mean is
n
{\displaystyle n}
divided by the sum of the reciprocal of each item in the list:
H
(
x
1
,
…
,
x
n
)
=
n
1
x
1
+
⋯
+
1
x
n
{\displaystyle H(x_{1},\ldots ,x_{n})={\frac {n}{{\frac {1}{x_{1}}}+\cdots +{\frac {1}{x_{n}}}}}}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #AppleScript | AppleScript | -- arithmetic_mean :: [Number] -> Number
on arithmetic_mean(xs)
-- sum :: Number -> Number -> Number
script sum
on |λ|(accumulator, x)
accumulator + x
end |λ|
end script
foldl(sum, 0, xs) / (length of xs)
end arithmetic_mean
-- geometric_mean :: [Number] -> Number
on geometric_mean(xs)
-- product :: Number -> Number -> Number
script product
on |λ|(accumulator, x)
accumulator * x
end |λ|
end script
foldl(product, 1, xs) ^ (1 / (length of xs))
end geometric_mean
-- harmonic_mean :: [Number] -> Number
on harmonic_mean(xs)
-- addInverse :: Number -> Number -> Number
script addInverse
on |λ|(accumulator, x)
accumulator + (1 / x)
end |λ|
end script
(length of xs) / (foldl(addInverse, 0, xs))
end harmonic_mean
-- TEST -----------------------------------------------------------------------
on run
set {A, G, H} to ap({arithmetic_mean, geometric_mean, harmonic_mean}, ¬
{{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}})
{values:{arithmetic:A, geometric:G, harmonic:H}, inequalities:¬
{|A >= G|:A ≥ G}, |G >= H|:G ≥ H}
end run
-- GENERIC FUNCTIONS ----------------------------------------------------------
-- A list of functions applied to a list of arguments
-- (<*> | ap) :: [(a -> b)] -> [a] -> [b]
on ap(fs, xs)
set {nf, nx} to {length of fs, length of xs}
set acc to {}
repeat with i from 1 to nf
tell mReturn(item i of fs)
repeat with j from 1 to nx
set end of acc to |λ|(contents of (item j of xs))
end repeat
end tell
end repeat
return acc
end ap
-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
tell mReturn(f)
set v to startValue
set lng to length of xs
repeat with i from 1 to lng
set v to |λ|(v, item i of xs, i, xs)
end repeat
return v
end tell
end foldl
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn |
http://rosettacode.org/wiki/Barnsley_fern | Barnsley fern |
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS).
Task
Create this fractal fern, using the following transformations:
ƒ1 (chosen 1% of the time)
xn + 1 = 0
yn + 1 = 0.16 yn
ƒ2 (chosen 85% of the time)
xn + 1 = 0.85 xn + 0.04 yn
yn + 1 = −0.04 xn + 0.85 yn + 1.6
ƒ3 (chosen 7% of the time)
xn + 1 = 0.2 xn − 0.26 yn
yn + 1 = 0.23 xn + 0.22 yn + 1.6
ƒ4 (chosen 7% of the time)
xn + 1 = −0.15 xn + 0.28 yn
yn + 1 = 0.26 xn + 0.24 yn + 0.44.
Starting position: x = 0, y = 0
| #Unicon | Unicon |
link graphics
global x, y
procedure main()
&window := open("FERN", "g", "size=400,400", "bg=black")
x := y := 0
repeat {
draw()
delay(30)
if *Pending() > 0 then {
case Event() of {
"q"|"\e": return
}
}
}
end
procedure next_point()
local nx, ny, r
nx := 0.0
ny := 0.0
r := ?100
if r < 1 then {
nx := 0.0
ny := 0.16 * y
} else if r < 86 then {
nx := 0.85 * x + 0.04 * y
ny := -0.04 * x + 0.85 * y + 1.6
} else if r < 93 then {
nx := 0.2 * x - 0.26 * y
ny := 0.23 * x + 0.22 * y + 1.6
} else {
nx := -0.15 * x + 0.28 * y
ny := 0.26 * x + 0.24 * y + 0.44
}
x := nx
y := ny
end
procedure map(v:real, a, b, c, d)
return (v - a) / (b - a) * (d - c) + c;
end
procedure draw_point()
local px, py
px := map(x, -2.1820, 2.6558, 0.0, 400.0)
py := map(y, 0.0, 9.9983, 400.0, 0.0)
Fg("green")
DrawPoint(px, py)
end
procedure draw()
every i := 0 to 10000 do {
draw_point()
next_point()
}
end
|
http://rosettacode.org/wiki/Babbage_problem | Babbage problem |
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
What is the smallest positive integer whose square ends in the digits 269,696?
— Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.
He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.
Task[edit]
The task is to find out if Babbage had the right answer — and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand.
As Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.
For these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].
Motivation
The aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.
| #FreeBASIC | FreeBASIC | ' version 25-10-2016
' compile with: fbc -s console
' Charles Babbage would have known that only number ending
' on a 4 or 6 could produce a square ending on a 6
' also any number below 520 would produce a square smaller than 269,696
' we can stop when we have reached 99,736
' we know it square and it ends on 269,696
Dim As ULong number = 524 ' first number to try
Dim As ULong square, count
Do
' square the number
square = number * number
' look at the last 6 digits, if they match print the number
If Right(Str(square), 6) = "269696" Then Exit Do
' increase the number with 2, number end ons a 6
number = number +2
' if the number = 99736 then we haved found a smaller number, so stop
If number = 99736 Then Exit Do
square = number * number
' look at the last 6 digits, if they match print the number
If Right(Str(square),6 ) = "269696" Then Exit Do
' increase the number with 8, number ends on a 4
number = number +8
' go to the first line under "Do"
Loop
If number = 99736 Then
Print "No smaller number was found"
Else
' we found a smaller number, print the number and its square
Print Using "The number = #####, and its square = ##########,"; number; square
End If
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End |
http://rosettacode.org/wiki/Averages/Mode | Averages/Mode | Task[edit]
Write a program to find the mode value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriate or possible to support an unspecified value type, use integers.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #APL | APL | mode←{{s←⌈/⍵[;2]⋄⊃¨(↓⍵)∩{⍵,s}¨⍵[;1]}{⍺,≢⍵}⌸⍵} |
http://rosettacode.org/wiki/Averages/Simple_moving_average | Averages/Simple moving average | Computing the simple moving average of a series of numbers.
Task[edit]
Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far.
Description
A simple moving average is a method for computing an average of a stream of numbers by only averaging the last P numbers from the stream, where P is known as the period.
It can be implemented by calling an initialing routine with P as its argument, I(P), which should then return a routine that when called with individual, successive members of a stream of numbers, computes the mean of (up to), the last P of them, lets call this SMA().
The word stateful in the task description refers to the need for SMA() to remember certain information between calls to it:
The period, P
An ordered container of at least the last P numbers from each of its individual calls.
Stateful also means that successive calls to I(), the initializer, should return separate routines that do not share saved state so they could be used on two independent streams of data.
Pseudo-code for an implementation of SMA is:
function SMA(number: N):
stateful integer: P
stateful list: stream
number: average
stream.append_last(N)
if stream.length() > P:
# Only average the last P elements of the stream
stream.delete_first()
if stream.length() == 0:
average = 0
else:
average = sum( stream.values() ) / stream.length()
return average
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Kotlin | Kotlin | // version 1.0.6
fun initMovingAverage(p: Int): (Double) -> Double {
if (p < 1) throw IllegalArgumentException("Period must be a positive integer")
val list = mutableListOf<Double>()
return {
list.add(it)
if (list.size > p) list.removeAt(0)
list.average()
}
}
fun main(args: Array<String>) {
val sma4 = initMovingAverage(4)
val sma5 = initMovingAverage(5)
val numbers = listOf(1.0, 2.0, 3.0, 4.0, 5.0, 5.0, 4.0, 3.0, 2.0, 1.0)
println("num\tsma4\tsma5\n")
for (number in numbers) println("${number}\t${sma4(number)}\t${sma5(number)}")
} |
http://rosettacode.org/wiki/Averages/Pythagorean_means | Averages/Pythagorean means | Task[edit]
Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive).
Show that
A
(
x
1
,
…
,
x
n
)
≥
G
(
x
1
,
…
,
x
n
)
≥
H
(
x
1
,
…
,
x
n
)
{\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})}
for this set of positive integers.
The most common of the three means, the arithmetic mean, is the sum of the list divided by its length:
A
(
x
1
,
…
,
x
n
)
=
x
1
+
⋯
+
x
n
n
{\displaystyle A(x_{1},\ldots ,x_{n})={\frac {x_{1}+\cdots +x_{n}}{n}}}
The geometric mean is the
n
{\displaystyle n}
th root of the product of the list:
G
(
x
1
,
…
,
x
n
)
=
x
1
⋯
x
n
n
{\displaystyle G(x_{1},\ldots ,x_{n})={\sqrt[{n}]{x_{1}\cdots x_{n}}}}
The harmonic mean is
n
{\displaystyle n}
divided by the sum of the reciprocal of each item in the list:
H
(
x
1
,
…
,
x
n
)
=
n
1
x
1
+
⋯
+
1
x
n
{\displaystyle H(x_{1},\ldots ,x_{n})={\frac {n}{{\frac {1}{x_{1}}}+\cdots +{\frac {1}{x_{n}}}}}}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Arturo | Arturo | arithmeticMean: function [arr]->
average arr
geometricMean: function [arr]->
(product arr) ^ 1//size arr
harmonicMean: function [arr]->
(size arr) // sum map arr 'i [1//i]
print arithmeticMean 1..10
print geometricMean 1..10
print harmonicMean 1..10 |
http://rosettacode.org/wiki/Barnsley_fern | Barnsley fern |
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS).
Task
Create this fractal fern, using the following transformations:
ƒ1 (chosen 1% of the time)
xn + 1 = 0
yn + 1 = 0.16 yn
ƒ2 (chosen 85% of the time)
xn + 1 = 0.85 xn + 0.04 yn
yn + 1 = −0.04 xn + 0.85 yn + 1.6
ƒ3 (chosen 7% of the time)
xn + 1 = 0.2 xn − 0.26 yn
yn + 1 = 0.23 xn + 0.22 yn + 1.6
ƒ4 (chosen 7% of the time)
xn + 1 = −0.15 xn + 0.28 yn
yn + 1 = 0.26 xn + 0.24 yn + 0.44.
Starting position: x = 0, y = 0
| #VBA | VBA | Private Sub plot_coordinate_pairs(x As Variant, y As Variant)
Dim chrt As Chart
Set chrt = ActiveSheet.Shapes.AddChart.Chart
With chrt
.ChartType = xlXYScatter
.HasLegend = False
.SeriesCollection.NewSeries
.SeriesCollection.Item(1).XValues = x
.SeriesCollection.Item(1).Values = y
End With
End Sub
Public Sub barnsley_fern()
Const MAX = 50000
Dim x(MAX) As Double
Dim y(MAX) As Double
x(0) = 0: y(0) = 0
For i = 1 To MAX
Select Case CInt(100 * Rnd)
Case 0 To 1
x(i) = 0
y(i) = 0.16 * y(i - 1)
Case 2 To 85
x(i) = 0.85 * x(i - 1) + 0.04 * y(i - 1)
y(i) = -0.04 * x(i - 1) + 0.85 * y(i - 1) + 1.6
Case 86 To 92
x(i) = 0.2 * x(i - 1) - 0.26 * y(i - 1)
y(i) = 0.23 * x(i - 1) + 0.22 * y(i - 1) + 1.6
Case 93 To 100
x(i) = -0.15 * x(i - 1) + 0.28 * y(i - 1)
y(i) = 0.26 * x(i - 1) + 0.24 * y(i - 1) + 0.44
End Select
Next i
plot_coordinate_pairs x, y
End Sub |
http://rosettacode.org/wiki/Babbage_problem | Babbage problem |
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
What is the smallest positive integer whose square ends in the digits 269,696?
— Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.
He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.
Task[edit]
The task is to find out if Babbage had the right answer — and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand.
As Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.
For these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].
Motivation
The aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.
| #Frink | Frink | // This is a solver for the Rosetta Code problem "Babbage problem"
// https://rosettacode.org/wiki/Babbage_problem
i = 1
while true
{
// mod is the modulus operator.
// The == operator is a test for equality. A single =
// assigns to a variable.
if i² mod million == 269696
{
// This prints i and i²
println[i + "² = " + i²]
exit[] // This terminates the program if a solution is found.
}
i = i + 1
} |
http://rosettacode.org/wiki/Averages/Mode | Averages/Mode | Task[edit]
Write a program to find the mode value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriate or possible to support an unspecified value type, use integers.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #AppleScript | AppleScript | use AppleScript version "2.3.1" -- Mac OS X 10.9 (Mavericks) or later (for these 'use' commands).
use sorter : script "Shell sort" -- https://www.rosettacode.org/wiki/Sorting_algorithms/Shell_sort#AppleScript
on modeOf(listOrRecord)
-- Extract and sort numbers and text separately, then concatenate the results to get a single list of values.
set theNumbers to listOrRecord's numbers
tell sorter to sort(theNumbers, 1, -1)
set theTexts to listOrRecord's text
tell sorter to sort(theTexts, 1, -1)
script o
property values : theNumbers & theTexts
property mode : {}
end script
-- Identify the most frequently occurring value(s).
if (o's values is not {}) then
set i to 1
set currentValue to beginning of o's values
set maxCount to 1
repeat with j from 2 to (count o's values)
set thisValue to item j of o's values
if (thisValue is not currentValue) then
set thisCount to j - i
if (thisCount > maxCount) then
set o's mode to {currentValue}
set maxCount to thisCount
else if (thisCount = maxCount) then
set end of o's mode to currentValue
end if
set i to j
set currentValue to thisValue
end if
end repeat
if (j + 1 - i > maxCount) then
set o's mode to {currentValue}
else if (j + 1 - i = maxCount) then
set end of o's mode to currentValue
end if
end if
return o's mode
end modeOf
-- Test code:
-- With a list:
modeOf({12, 4, "rhubarb", 88, "rhubarb", 17, "custard", 4.0, 4, 88, "rhubarb"})
--> {4, "rhubarb"}
-- With a record:
modeOf({a:12, b:4, c:"rhubarb", d:88, e:"rhubarb", f:17, g:"custard", h:4.0, i:4, j:88})
--> {4} |
http://rosettacode.org/wiki/Averages/Simple_moving_average | Averages/Simple moving average | Computing the simple moving average of a series of numbers.
Task[edit]
Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far.
Description
A simple moving average is a method for computing an average of a stream of numbers by only averaging the last P numbers from the stream, where P is known as the period.
It can be implemented by calling an initialing routine with P as its argument, I(P), which should then return a routine that when called with individual, successive members of a stream of numbers, computes the mean of (up to), the last P of them, lets call this SMA().
The word stateful in the task description refers to the need for SMA() to remember certain information between calls to it:
The period, P
An ordered container of at least the last P numbers from each of its individual calls.
Stateful also means that successive calls to I(), the initializer, should return separate routines that do not share saved state so they could be used on two independent streams of data.
Pseudo-code for an implementation of SMA is:
function SMA(number: N):
stateful integer: P
stateful list: stream
number: average
stream.append_last(N)
if stream.length() > P:
# Only average the last P elements of the stream
stream.delete_first()
if stream.length() == 0:
average = 0
else:
average = sum( stream.values() ) / stream.length()
return average
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Lasso | Lasso | define simple_moving_average(a::array,s::integer)::decimal => {
#a->size == 0 ? return 0.00
#s == 0 ? return 0.00
#a->size == 1 ? return decimal(#a->first)
#s == 1 ? return decimal(#a->last)
local(na = array)
if(#a->size <= #s) => {
#na = #a
else
local(ar = #a->ascopy)
#ar->reverse
loop(#s) => { #na->insert(#ar->get(loop_count)) }
}
#s > #na->size ? #s = #na->size
return (with e in #na sum #e) / decimal(#s)
}
// tests:
'SMA 3 on array(1,2,3,4,5,5,4,3,2,1): '
simple_moving_average(array(1,2,3,4,5,5,4,3,2,1),3)
'\rSMA 5 on array(1,2,3,4,5,5,4,3,2,1): '
simple_moving_average(array(1,2,3,4,5,5,4,3,2,1),5)
'\r\rFurther example: \r'
local(mynumbers = array, sma_num = 5)
loop(10) => {^
#mynumbers->insert(integer_random(1,100))
#mynumbers->size + ' numbers: ' + #mynumbers
' SMA3 is: ' + simple_moving_average(#mynumbers,3)
', SMA5 is: ' + simple_moving_average(#mynumbers,5)
'\r'
^} |
http://rosettacode.org/wiki/Averages/Pythagorean_means | Averages/Pythagorean means | Task[edit]
Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive).
Show that
A
(
x
1
,
…
,
x
n
)
≥
G
(
x
1
,
…
,
x
n
)
≥
H
(
x
1
,
…
,
x
n
)
{\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})}
for this set of positive integers.
The most common of the three means, the arithmetic mean, is the sum of the list divided by its length:
A
(
x
1
,
…
,
x
n
)
=
x
1
+
⋯
+
x
n
n
{\displaystyle A(x_{1},\ldots ,x_{n})={\frac {x_{1}+\cdots +x_{n}}{n}}}
The geometric mean is the
n
{\displaystyle n}
th root of the product of the list:
G
(
x
1
,
…
,
x
n
)
=
x
1
⋯
x
n
n
{\displaystyle G(x_{1},\ldots ,x_{n})={\sqrt[{n}]{x_{1}\cdots x_{n}}}}
The harmonic mean is
n
{\displaystyle n}
divided by the sum of the reciprocal of each item in the list:
H
(
x
1
,
…
,
x
n
)
=
n
1
x
1
+
⋯
+
1
x
n
{\displaystyle H(x_{1},\ldots ,x_{n})={\frac {n}{{\frac {1}{x_{1}}}+\cdots +{\frac {1}{x_{n}}}}}}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #AutoHotkey | AutoHotkey | A := ArithmeticMean(1, 10)
G := GeometricMean(1, 10)
H := HarmonicMean(1, 10)
If G Between %H% And %A%
Result := "True"
Else
Result := "False"
MsgBox, %A%`n%G%`n%H%`n%Result%
;---------------------------------------------------------------------------
ArithmeticMean(a, b) { ; of integers a through b
;---------------------------------------------------------------------------
n := b - a + 1
Loop, %n%
Sum += (a + A_Index - 1)
Return, Sum / n
}
;---------------------------------------------------------------------------
GeometricMean(a, b) { ; of integers a through b
;---------------------------------------------------------------------------
n := b - a + 1
Prod := 1
Loop, %n%
Prod *= (a + A_Index - 1)
Return, Prod ** (1 / n)
}
;---------------------------------------------------------------------------
HarmonicMean(a, b) { ; of integers a through b
;---------------------------------------------------------------------------
n := b - a + 1
Loop, %n%
Sum += 1 / (a + A_Index - 1)
Return, n / Sum
} |
http://rosettacode.org/wiki/Barnsley_fern | Barnsley fern |
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS).
Task
Create this fractal fern, using the following transformations:
ƒ1 (chosen 1% of the time)
xn + 1 = 0
yn + 1 = 0.16 yn
ƒ2 (chosen 85% of the time)
xn + 1 = 0.85 xn + 0.04 yn
yn + 1 = −0.04 xn + 0.85 yn + 1.6
ƒ3 (chosen 7% of the time)
xn + 1 = 0.2 xn − 0.26 yn
yn + 1 = 0.23 xn + 0.22 yn + 1.6
ƒ4 (chosen 7% of the time)
xn + 1 = −0.15 xn + 0.28 yn
yn + 1 = 0.26 xn + 0.24 yn + 0.44.
Starting position: x = 0, y = 0
| #Visual_Basic_.NET | Visual Basic .NET | ' Barnsley Fern - 11/11/2019
Public Class BarnsleyFern
Private Sub BarnsleyFern_Paint(sender As Object, e As PaintEventArgs) Handles Me.Paint
Const Height = 800
Dim x, y, xn, yn As Double
Dim f As Double = Height / 10.6
Dim offset_x As UInteger = Height \ 4 - Height \ 40
Dim n, r As UInteger
Dim Bmp As New Drawing.Bitmap(Height \ 2, Height) 'x,y
'In Form: xPictureBox As PictureBox(800,400)
xPictureBox.Image = Bmp
For n = 1 To Height * 50
r = Int(Rnd() * 100) ' f from 0 to 99
Select Case r
Case 0 To 84
xn = 0.85 * x + 0.04 * y
yn = -0.04 * x + 0.85 * y + 1.6
Case 85 To 91
xn = 0.2 * x - 0.26 * y
yn = 0.23 * x + 0.22 * y + 1.6
Case 92 To 98
xn = -0.15 * x + 0.28 * y
yn = 0.26 * x + 0.24 * y + 0.44
Case Else
xn = 0
yn = 0.16 * y
End Select
x = xn : y = yn
Bmp.SetPixel(offset_x + x * f, Height - y * f, Color.FromArgb(0, 255, 0)) 'x,y 'r,g,b
Next n
End Sub 'Paint
End Class 'BarnsleyFern |
http://rosettacode.org/wiki/Babbage_problem | Babbage problem |
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
What is the smallest positive integer whose square ends in the digits 269,696?
— Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.
He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.
Task[edit]
The task is to find out if Babbage had the right answer — and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand.
As Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.
For these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].
Motivation
The aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.
| #FutureBasic | FutureBasic | window 1
long i
for i = 1 to 1000000
if i ^ 2 mod 1000000 == 269696 then exit for
next
print @"The smallest number whose square ends in 269696 is ";i
print @"Its square is ";i ^ 2
HandleEvents |
http://rosettacode.org/wiki/Averages/Mode | Averages/Mode | Task[edit]
Write a program to find the mode value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriate or possible to support an unspecified value type, use integers.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Arturo | Arturo | getMode: function [arr][
freqs: new #[]
loop arr 'i [
k: to :string i
if not? key? freqs k -> set freqs k 0
freqs\[k]: (freqs\[k]) + 1
]
maximum: max values freqs
select keys freqs 'i -> maximum = freqs\[i]
]
print getMode [1 3 6 6 6 6 7 7 12 12 17]
print getMode [1 1 2 4 4] |
http://rosettacode.org/wiki/Averages/Simple_moving_average | Averages/Simple moving average | Computing the simple moving average of a series of numbers.
Task[edit]
Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far.
Description
A simple moving average is a method for computing an average of a stream of numbers by only averaging the last P numbers from the stream, where P is known as the period.
It can be implemented by calling an initialing routine with P as its argument, I(P), which should then return a routine that when called with individual, successive members of a stream of numbers, computes the mean of (up to), the last P of them, lets call this SMA().
The word stateful in the task description refers to the need for SMA() to remember certain information between calls to it:
The period, P
An ordered container of at least the last P numbers from each of its individual calls.
Stateful also means that successive calls to I(), the initializer, should return separate routines that do not share saved state so they could be used on two independent streams of data.
Pseudo-code for an implementation of SMA is:
function SMA(number: N):
stateful integer: P
stateful list: stream
number: average
stream.append_last(N)
if stream.length() > P:
# Only average the last P elements of the stream
stream.delete_first()
if stream.length() == 0:
average = 0
else:
average = sum( stream.values() ) / stream.length()
return average
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Liberty_BASIC | Liberty BASIC |
dim v$( 100) ' Each array term stores a particular SMA of period p in p*10 bytes
nomainwin
WindowWidth =1080
WindowHeight = 780
graphicbox #w.gb1, 20, 20, 1000, 700
open "Running averages to smooth data" for window as #w
#w "trapclose quit"
#w.gb1 "down"
old.x = 0
old.y.orig =500 ' black
old.y.3.SMA =350 ' red
old.y.20.SMA =300 ' green
for i =0 to 999 step 1
scan
v =1.1 +sin( i /1000 *2 *3.14159265) + 0.2 *rnd( 1) ' sin wave with added random noise
x =i /6.28318 *1000
y.orig =500 -v /2.5 *500
#w.gb1 "color black ; down ; line "; i-1; " "; old.y.orig; " "; i; " "; y.orig; " ; up"
y.3.SMA =500 -SMA( 1, v, 3) /2.5 *500 ' SMA given ID of 1 is to do 3-term running average
#w.gb1 "color red ; down ; line "; i-1; " "; old.y.3.SMA +50; " "; i; " "; y.3.SMA +50; " ; up"
y.20.SMA =500 -SMA( 2, v, 20) /2.5 *500 ' SMA given ID of 2 is to do 20-term running average
#w.gb1 "color green ; down ; line "; i-1; " "; old.y.20.SMA +100; " "; i; " "; y.20.SMA +100; " ; up"
'print "Supplied with "; v; ", so SMAs are now "; using( "###.###", SMA( 1, v, 3)); " over 3 terms or "; using( "###.###", SMA( 2, v, 5)) ; " over 5 terms." ' ID, latest data, period
old.y.orig =y.orig
old.y.3.SMA =y.3.SMA
old.y.20.SMA =y.20.SMA
next i
wait
sub quit j$
close #w
end
end sub
function SMA( ID, Number, Period)
v$( ID) =right$( " " +str$( Number), 10) +v$( ID) ' add new number at left, lose last number on right
v$( ID) =left$( v$( ID), Period *10)
'print "{"; v$( ID); "}",
k =0 ' number of terms read
total =0 ' sum of terms read
do
p$ =mid$( v$( ID), 1 +k *10, 10)
if p$ ="" then exit do
vv =val( p$)
total =total +vv
k =k +1
loop until p$ =""
if k <Period then SMA =total / k else SMA =total /Period
end function
|
http://rosettacode.org/wiki/Averages/Pythagorean_means | Averages/Pythagorean means | Task[edit]
Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive).
Show that
A
(
x
1
,
…
,
x
n
)
≥
G
(
x
1
,
…
,
x
n
)
≥
H
(
x
1
,
…
,
x
n
)
{\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})}
for this set of positive integers.
The most common of the three means, the arithmetic mean, is the sum of the list divided by its length:
A
(
x
1
,
…
,
x
n
)
=
x
1
+
⋯
+
x
n
n
{\displaystyle A(x_{1},\ldots ,x_{n})={\frac {x_{1}+\cdots +x_{n}}{n}}}
The geometric mean is the
n
{\displaystyle n}
th root of the product of the list:
G
(
x
1
,
…
,
x
n
)
=
x
1
⋯
x
n
n
{\displaystyle G(x_{1},\ldots ,x_{n})={\sqrt[{n}]{x_{1}\cdots x_{n}}}}
The harmonic mean is
n
{\displaystyle n}
divided by the sum of the reciprocal of each item in the list:
H
(
x
1
,
…
,
x
n
)
=
n
1
x
1
+
⋯
+
1
x
n
{\displaystyle H(x_{1},\ldots ,x_{n})={\frac {n}{{\frac {1}{x_{1}}}+\cdots +{\frac {1}{x_{n}}}}}}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #AWK | AWK | #!/usr/bin/awk -f
{
x = $1; # value of 1st column
A += x;
G += log(x);
H += 1/x;
N++;
}
END {
print "Arithmethic mean: ",A/N;
print "Geometric mean : ",exp(G/N);
print "Harmonic mean : ",N/H;
} |
http://rosettacode.org/wiki/Barnsley_fern | Barnsley fern |
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS).
Task
Create this fractal fern, using the following transformations:
ƒ1 (chosen 1% of the time)
xn + 1 = 0
yn + 1 = 0.16 yn
ƒ2 (chosen 85% of the time)
xn + 1 = 0.85 xn + 0.04 yn
yn + 1 = −0.04 xn + 0.85 yn + 1.6
ƒ3 (chosen 7% of the time)
xn + 1 = 0.2 xn − 0.26 yn
yn + 1 = 0.23 xn + 0.22 yn + 1.6
ƒ4 (chosen 7% of the time)
xn + 1 = −0.15 xn + 0.28 yn
yn + 1 = 0.26 xn + 0.24 yn + 0.44.
Starting position: x = 0, y = 0
| #Wren | Wren | import "graphics" for Canvas, Color
import "dome" for Window
import "random" for Random
var Rand = Random.new()
class BarnsleyFern {
construct new(width, height, points) {
Window.title = "Barnsley Fern"
Window.resize(width, height)
Canvas.resize(width, height)
_w = width
_h = height
_n = points
}
init() {
createFern()
}
createFern() {
var x = 0
var y = 0
var c = Color.hex("#32cd32")
for (i in 0..._n) {
var tx
var ty
var r = Rand.float()
if (r <= 0.01) {
tx = 0
ty = 0.16 * y
} else if (r <= 0.86) {
tx = 0.85 * x + 0.04 * y
ty = -0.04 * x + 0.85 * y + 1.6
} else if (r <= 0.93) {
tx = 0.2 * x - 0.26 * y
ty = 0.23 * x + 0.22 * y + 1.6
} else {
tx = -0.15 * x + 0.28 * y
ty = 0.26 * x + 0.24 * y + 0.44
}
x = tx
y = ty
Canvas.pset((_w/2 + x * _w/11).round, (_h - y * _h/11).round, c)
}
}
update() {}
draw(alpha) {}
}
var Game = BarnsleyFern.new(640, 640, 200000) |
http://rosettacode.org/wiki/Babbage_problem | Babbage problem |
Charles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
What is the smallest positive integer whose square ends in the digits 269,696?
— Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.
He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.
Task[edit]
The task is to find out if Babbage had the right answer — and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand.
As Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.
For these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].
Motivation
The aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | Public Sub Main()
Dim iNum As Long
For iNum = 1 To 100000
If Str(iNum * iNum) Ends "269696" Then Break
Next
Print "The lowest number squared that ends in '269696' is " & Str(iNum)
End |
http://rosettacode.org/wiki/Balanced_brackets | Balanced brackets | Task:
Generate a string with N opening brackets [ and with N closing brackets ], in some arbitrary order.
Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.
Examples
(empty) OK
[] OK
[][] OK
[[][]] OK
][ NOT OK
][][ NOT OK
[]][[] NOT OK
| #11l | 11l | F gen(n)
V txt = [‘[’, ‘]’] * n
random:shuffle(&txt)
R txt.join(‘’)
F is_balanced(s)
V nesting_level = 0
L(c) s
S c
‘[’
nesting_level++
‘]’
I --nesting_level < 0
R 0B
R 1B
L(n) 0..9
V s = gen(n)
print(s‘’(‘ ’ * (20 - s.len))‘is ’(I is_balanced(s) {‘balanced’} E ‘not balanced’)) |
http://rosettacode.org/wiki/Averages/Mode | Averages/Mode | Task[edit]
Write a program to find the mode value of a collection.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriate or possible to support an unspecified value type, use integers.
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #AutoHotkey | AutoHotkey | MsgBox % Mode("1 2 3")
MsgBox % Mode("1 2 0 3 0.0")
MsgBox % Mode("0.1 2.2 -0.1 0.22e1 2.20 0.1")
Mode(a, d=" ") { ; the number that occurs most frequently in a list delimited by d (space)
Sort a, ND%d%
Loop Parse, a, %d%
If (V != A_LoopField) {
If (Ct > MxCt)
MxV := V, MxCt := Ct
V := A_LoopField, Ct := 1
}
Else Ct++
Return Ct>MxCt ? V : MxV
} |
http://rosettacode.org/wiki/Averages/Simple_moving_average | Averages/Simple moving average | Computing the simple moving average of a series of numbers.
Task[edit]
Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far.
Description
A simple moving average is a method for computing an average of a stream of numbers by only averaging the last P numbers from the stream, where P is known as the period.
It can be implemented by calling an initialing routine with P as its argument, I(P), which should then return a routine that when called with individual, successive members of a stream of numbers, computes the mean of (up to), the last P of them, lets call this SMA().
The word stateful in the task description refers to the need for SMA() to remember certain information between calls to it:
The period, P
An ordered container of at least the last P numbers from each of its individual calls.
Stateful also means that successive calls to I(), the initializer, should return separate routines that do not share saved state so they could be used on two independent streams of data.
Pseudo-code for an implementation of SMA is:
function SMA(number: N):
stateful integer: P
stateful list: stream
number: average
stream.append_last(N)
if stream.length() > P:
# Only average the last P elements of the stream
stream.delete_first()
if stream.length() == 0:
average = 0
else:
average = sum( stream.values() ) / stream.length()
return average
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #Logo | Logo | to average :l
output quotient apply "sum :l count :l
end
to make.sma :name :period
localmake "qn word :name ".queue
make :qn []
define :name `[ [n] ; parameter list
[if equal? count :,:qn ,:period [ignore dequeue ",:qn]]
[queue ",:qn :n]
[output average :,:qn]
]
end
make.sma "avg3 3
show map "avg3 [1 2 3 4 5] ; [1 1.5 2 3 4]
show text "avg3 ; examine what substitutions took place
[[n] [if equal? count :avg3.queue 3 [ignore dequeue "avg3.queue]] [queue "avg3.queue :n] [output average :avg3.queue]]
; the internal queue is in the global namespace, easy to inspect
show :avg3.queue ; [3 4 5] |
http://rosettacode.org/wiki/Averages/Pythagorean_means | Averages/Pythagorean means | Task[edit]
Compute all three of the Pythagorean means of the set of integers 1 through 10 (inclusive).
Show that
A
(
x
1
,
…
,
x
n
)
≥
G
(
x
1
,
…
,
x
n
)
≥
H
(
x
1
,
…
,
x
n
)
{\displaystyle A(x_{1},\ldots ,x_{n})\geq G(x_{1},\ldots ,x_{n})\geq H(x_{1},\ldots ,x_{n})}
for this set of positive integers.
The most common of the three means, the arithmetic mean, is the sum of the list divided by its length:
A
(
x
1
,
…
,
x
n
)
=
x
1
+
⋯
+
x
n
n
{\displaystyle A(x_{1},\ldots ,x_{n})={\frac {x_{1}+\cdots +x_{n}}{n}}}
The geometric mean is the
n
{\displaystyle n}
th root of the product of the list:
G
(
x
1
,
…
,
x
n
)
=
x
1
⋯
x
n
n
{\displaystyle G(x_{1},\ldots ,x_{n})={\sqrt[{n}]{x_{1}\cdots x_{n}}}}
The harmonic mean is
n
{\displaystyle n}
divided by the sum of the reciprocal of each item in the list:
H
(
x
1
,
…
,
x
n
)
=
n
1
x
1
+
⋯
+
1
x
n
{\displaystyle H(x_{1},\ldots ,x_{n})={\frac {n}{{\frac {1}{x_{1}}}+\cdots +{\frac {1}{x_{n}}}}}}
See also
Tasks for calculating statistical measures
in one go
moving (sliding window)
moving (cumulative)
Mean
Arithmetic
Statistics/Basic
Averages/Arithmetic mean
Averages/Pythagorean means
Averages/Simple moving average
Geometric
Averages/Pythagorean means
Harmonic
Averages/Pythagorean means
Quadratic
Averages/Root mean square
Circular
Averages/Mean angle
Averages/Mean time of day
Median
Averages/Median
Mode
Averages/Mode
Standard deviation
Statistics/Basic
Cumulative standard deviation
| #BBC_BASIC | BBC BASIC | DIM a(9)
a() = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
PRINT "Arithmetic mean = " ; FNarithmeticmean(a())
PRINT "Geometric mean = " ; FNgeometricmean(a())
PRINT "Harmonic mean = " ; FNharmonicmean(a())
END
DEF FNarithmeticmean(a())
= SUM(a()) / (DIM(a(),1)+1)
DEF FNgeometricmean(a())
LOCAL a, I%
a = 1
FOR I% = 0 TO DIM(a(),1)
a *= a(I%)
NEXT
= a ^ (1/(DIM(a(),1)+1))
DEF FNharmonicmean(a())
LOCAL b()
DIM b(DIM(a(),1))
b() = 1/a()
= (DIM(a(),1)+1) / SUM(b())
|
http://rosettacode.org/wiki/Barnsley_fern | Barnsley fern |
A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS).
Task
Create this fractal fern, using the following transformations:
ƒ1 (chosen 1% of the time)
xn + 1 = 0
yn + 1 = 0.16 yn
ƒ2 (chosen 85% of the time)
xn + 1 = 0.85 xn + 0.04 yn
yn + 1 = −0.04 xn + 0.85 yn + 1.6
ƒ3 (chosen 7% of the time)
xn + 1 = 0.2 xn − 0.26 yn
yn + 1 = 0.23 xn + 0.22 yn + 1.6
ƒ4 (chosen 7% of the time)
xn + 1 = −0.15 xn + 0.28 yn
yn + 1 = 0.26 xn + 0.24 yn + 0.44.
Starting position: x = 0, y = 0
| #XPL0 | XPL0 | int N, R;
real NX, NY, X, Y;
[SetVid($12); \set 640x480x4 VGA graphics (on PC or RPi)
X:= 0.0; Y:= 0.0;
for N:= 0 to 200_000 do
[R:= Ran(100); \0..99
case of
R < 1: [NX:= 0.0; NY:= 0.16*Y];
R < 8: [NX:= 0.20*X - 0.26*Y; NY:= 0.23*X + 0.22*Y + 1.60];
R < 15: [NX:=-0.15*X + 0.28*Y; NY:= 0.26*X + 0.24*Y + 0.44]
other [NX:= 0.85*X + 0.04*Y; NY:=-0.04*X + 0.85*Y + 1.60];
X:= NX; Y:= NY;
Point(320+fix(X*40.0), 440-fix(Y*40.0), 2\green\);
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.