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
| #.D0.9C.D0.9A-61.2F52 | МК-61/52 | 0 П0 П1 С/П x^2 ИП0 x^2 ИП1 *
+ ИП1 1 + П1 / КвКор П0 БП
03 |
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
| #Morfa | Morfa |
import morfa.base;
import morfa.functional.base;
template <TRange>
func rms(d: TRange): float
{
var count = 1;
return sqrt(reduce( (a: float, b: float) { count += 1; return a + b * b; }, d) / count);
}
func main(): void
{
println(rms(1 .. 11));
}
|
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.
| #Aime | Aime | integer i;
i = sqrt(269696);
while (i * i % 1000000 != 269696) {
i += 1;
}
o_(i, "\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
| #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
namespace SMA {
class Program {
static void Main(string[] args) {
var nums = Enumerable.Range(1, 5).Select(n => (double)n);
nums = nums.Concat(nums.Reverse());
var sma3 = SMA(3);
var sma5 = SMA(5);
foreach (var n in nums) {
Console.WriteLine("{0} (sma3) {1,-16} (sma5) {2,-16}", n, sma3(n), sma5(n));
}
}
static Func<double, double> SMA(int p) {
Queue<double> s = new Queue<double>(p);
return (x) => {
if (s.Count >= p) {
s.Dequeue();
}
s.Enqueue(x);
return s.Average();
};
}
}
} |
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
| #J | J | require 'plot'
f=: |: 0 ". ];._2 noun define
0 0 0 0.16 0 0 0.01
0.85 -0.04 0.04 0.85 0 1.60 0.85
0.20 0.23 -0.26 0.22 0 1.60 0.07
-0.15 0.26 0.28 0.24 0 0.44 0.07
)
fm=: {&(|: 2 2 $ f)
fa=: {&(|: 4 5 { f)
prob=: (+/\ 6 { f) I. ?@0:
ifs=: (fa@] + fm@] +/ .* [) prob
getPoints=: ifs^:(<200000)
plotFern=: 'dot;grids 0 0;tics 0 0;labels 0 0;color green' plot ;/@|:
plotFern getPoints 0 0 |
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
| #Nemerle | Nemerle | using System;
using System.Console;
using System.Math;
module RMS
{
RMS(x : list[int]) : double
{
def sum = x.Map(fun (x) {x*x}).FoldLeft(0, _+_);
Sqrt((sum :> double) / x.Length)
}
Main() : void
{
WriteLine("RMS of [1 .. 10]: {0:g6}", 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
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary
parse arg maxV .
if maxV = '' | maxV = '.' then maxV = 10
sum = 0
loop nr = 1 for maxV
sum = sum + nr ** 2
end nr
rmsD = Math.sqrt(sum / maxV)
say 'RMS of values from 1 to' maxV':' rmsD
return
|
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.
| #ALGOL_68 | ALGOL 68 | COMMENT text between pairs of words 'comment' in capitals are
for the human reader's information and are ignored by the machine
COMMENT
COMMENT Define s to be the integer value 269 696 COMMENT
INT s = 269 696;
COMMENT Name a location in the machine's storage area that will be
used to hold integer values.
The value stored in the location will change during the
calculations.
Note, "*" is used to represent the multiplication operator.
":=" causes the location named to the left of ":=" to
assume the value computed by the expression to the right.
"sqrt" computes an approximation to the square root
of the supplied parameter
"MOD" is an operator that computes the modulus of its
left operand with respect to its right operand
"ENTIER" is a unary operator that yields the largest
integer that is at most its operand.
COMMENT
INT v := ENTIER sqrt( s );
COMMENT the construct: WHILE...DO...OD repeatedly executes the
instructions between DO and OD, the execution stops when
the instructions between WHILE and DO yield the value FALSE.
COMMENT
WHILE ( v * v ) MOD 1 000 000 /= s DO v := v + 1 OD;
COMMENT print displays the values of its parameters
COMMENT
print( ( v, " when squared is: ", v * v, newline ) ) |
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
| #C.2B.2B | C++ |
#include <iostream>
#include <stddef.h>
#include <assert.h>
using std::cout;
using std::endl;
class SMA {
public:
SMA(unsigned int period) :
period(period), window(new double[period]), head(NULL), tail(NULL),
total(0) {
assert(period >= 1);
}
~SMA() {
delete[] window;
}
// Adds a value to the average, pushing one out if nescessary
void add(double val) {
// Special case: Initialization
if (head == NULL) {
head = window;
*head = val;
tail = head;
inc(tail);
total = val;
return;
}
// Were we already full?
if (head == tail) {
// Fix total-cache
total -= *head;
// Make room
inc(head);
}
// Write the value in the next spot.
*tail = val;
inc(tail);
// Update our total-cache
total += val;
}
// Returns the average of the last P elements added to this SMA.
// If no elements have been added yet, returns 0.0
double avg() const {
ptrdiff_t size = this->size();
if (size == 0) {
return 0; // No entries => 0 average
}
return total / (double) size; // Cast to double for floating point arithmetic
}
private:
unsigned int period;
double * window; // Holds the values to calculate the average of.
// Logically, head is before tail
double * head; // Points at the oldest element we've stored.
double * tail; // Points at the newest element we've stored.
double total; // Cache the total so we don't sum everything each time.
// Bumps the given pointer up by one.
// Wraps to the start of the array if needed.
void inc(double * & p) {
if (++p >= window + period) {
p = window;
}
}
// Returns how many numbers we have stored.
ptrdiff_t size() const {
if (head == NULL)
return 0;
if (head == tail)
return period;
return (period + tail - head) % period;
}
};
int main(int argc, char * * argv) {
SMA foo(3);
SMA bar(5);
int data[] = { 1, 2, 3, 4, 5, 5, 4, 3, 2, 1 };
for (int * itr = data; itr < data + 10; itr++) {
foo.add(*itr);
cout << "Added " << *itr << " avg: " << foo.avg() << endl;
}
cout << endl;
for (int * itr = data; itr < data + 10; itr++) {
bar.add(*itr);
cout << "Added " << *itr << " avg: " << bar.avg() << endl;
}
return 0;
}
|
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
| #Java | Java | import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class BarnsleyFern extends JPanel {
BufferedImage img;
public BarnsleyFern() {
final int dim = 640;
setPreferredSize(new Dimension(dim, dim));
setBackground(Color.white);
img = new BufferedImage(dim, dim, BufferedImage.TYPE_INT_ARGB);
createFern(dim, dim);
}
void createFern(int w, int h) {
double x = 0;
double y = 0;
for (int i = 0; i < 200_000; i++) {
double tmpx, tmpy;
double 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((int) Math.round(w / 2 + x * w / 11),
(int) Math.round(h - y * h / 11), 0xFF32CD32);
}
}
@Override
public void paintComponent(Graphics gg) {
super.paintComponent(gg);
Graphics2D g = (Graphics2D) gg;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.drawImage(img, 0, 0, null);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Barnsley Fern");
f.setResizable(false);
f.add(new BarnsleyFern(), BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.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
| #Nim | Nim | from math import sqrt, sum
from sequtils import mapIt
proc qmean(num: seq[float]): float =
result = num.mapIt(it * it).sum
result = sqrt(result / float(num.len))
echo qmean(@[1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0]) |
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
| #Oberon-2 | Oberon-2 |
MODULE QM;
IMPORT ML := MathL, Out;
VAR
nums: ARRAY 10 OF LONGREAL;
i: INTEGER;
PROCEDURE Rms(a: ARRAY OF LONGREAL): LONGREAL;
VAR
i: INTEGER;
s: LONGREAL;
BEGIN
s := 0.0;
FOR i := 0 TO LEN(a) - 1 DO
s := s + (a[i] * a[i])
END;
RETURN ML.Sqrt(s / LEN(a))
END Rms;
BEGIN
FOR i := 0 TO LEN(nums) - 1 DO
nums[i] := i + 1
END;
Out.String("Quadratic Mean: ");Out.LongReal(Rms(nums));Out.Ln
END QM.
|
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.
| #APL | APL | ⍝ We know that 99,736 is a valid answer, so we only need to test the positive integers from 1 up to there:
N←⍳99736
⍝ The SQUARE OF omega is omega times omega:
SQUAREOF←{⍵×⍵}
⍝ To say that alpha ENDS IN the six-digit number omega means that alpha divided by 1,000,000 leaves remainder omega:
ENDSIN←{(1000000|⍺)=⍵}
⍝ The SMALLEST number WHERE some condition is met is found by taking the first number from a list of attempts, after rearranging the list so that numbers satisfying the condition come before those that fail to satisfy it:
SMALLESTWHERE←{1↑⍒⍵}
⍝ We can now ask the computer for the answer:
SMALLESTWHERE (SQUAREOF N) ENDSIN 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
| #Clojure | Clojure | (import '[clojure.lang PersistentQueue])
(defn enqueue-max [q p n]
(let [q (conj q n)]
(if (<= (count q) p) q (pop q))))
(defn avg [coll] (/ (reduce + coll) (count coll)))
(defn init-moving-avg [p]
(let [state (atom PersistentQueue/EMPTY)]
(fn [n]
(avg (swap! state enqueue-max p n))))) |
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
| #JavaScript | JavaScript | // Barnsley fern fractal
//6/17/16 aev
function pBarnsleyFern(canvasId, lim) {
// DCLs
var canvas = document.getElementById(canvasId);
var ctx = canvas.getContext("2d");
var w = canvas.width;
var h = canvas.height;
var x = 0.,
y = 0.,
xw = 0.,
yw = 0.,
r;
// Like in PARI/GP: return random number 0..max-1
function randgp(max) {
return Math.floor(Math.random() * max)
}
// Clean canvas
ctx.fillStyle = "white";
ctx.fillRect(0, 0, w, h);
// MAIN LOOP
for (var i = 0; i < lim; i++) {
r = randgp(100);
if (r <= 1) {
xw = 0;
yw = 0.16 * y;
} else if (r <= 8) {
xw = 0.2 * x - 0.26 * y;
yw = 0.23 * x + 0.22 * y + 1.6;
} else if (r <= 15) {
xw = -0.15 * x + 0.28 * y;
yw = 0.26 * x + 0.24 * y + 0.44;
} else {
xw = 0.85 * x + 0.04 * y;
yw = -0.04 * x + 0.85 * y + 1.6;
}
x = xw;
y = yw;
ctx.fillStyle = "green";
ctx.fillRect(x * 50 + 260, -y * 50 + 540, 1, 1);
} //fend i
} |
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
| #Objeck | Objeck | bundle Default {
class Hello {
function : Main(args : String[]) ~ Nil {
values := [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0];
RootSquareMean(values)->PrintLine();
}
function : native : RootSquareMean(values : Float[]) ~ Float {
sum := 0.0;
each(i : values) {
x := values[i]->Power(2.0);
sum += values[i]->Power(2.0);
};
return (sum / values->Size())->SquareRoot();
}
}
} |
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.
| #AppleScript | AppleScript | -- BABBAGE -------------------------------------------------------------------
-- babbage :: Int -> [Int]
on babbage(intTests)
script test
on toSquare(x)
(x * 1000000) + 269696
end toSquare
on |λ|(x)
hasIntRoot(toSquare(x))
end |λ|
end script
script toRoot
on |λ|(x)
((x * 1000000) + 269696) ^ (1 / 2)
end |λ|
end script
set xs to filter(test, enumFromTo(1, intTests))
zip(map(toRoot, xs), map(test's toSquare, xs))
end babbage
-- TEST ----------------------------------------------------------------------
on run
-- Try 1000 candidates
unlines(map(curry(intercalate)'s |λ|(" -> "), babbage(1000)))
--> "2.5264E+4 -> 6.38269696E+8"
end run
-- GENERIC FUNCTIONS ---------------------------------------------------------
-- curry :: (Script|Handler) -> Script
on curry(f)
script
on |λ|(a)
script
on |λ|(b)
|λ|(a, b) of mReturn(f)
end |λ|
end script
end |λ|
end script
end curry
-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
if m > n then
set d to -1
else
set d to 1
end if
set lst to {}
repeat with i from m to n by d
set end of lst to i
end repeat
return lst
end enumFromTo
-- filter :: (a -> Bool) -> [a] -> [a]
on filter(f, xs)
tell mReturn(f)
set lst to {}
set lng to length of xs
repeat with i from 1 to lng
set v to item i of xs
if |λ|(v, i, xs) then set end of lst to v
end repeat
return lst
end tell
end filter
-- hasIntRoot :: Int -> Bool
on hasIntRoot(n)
set r to n ^ 0.5
r = (r as integer)
end hasIntRoot
-- intercalate :: Text -> [Text] -> Text
on intercalate(strText, lstText)
set {dlm, my text item delimiters} to {my text item delimiters, strText}
set strJoined to lstText as text
set my text item delimiters to dlm
return strJoined
end intercalate
-- 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
-- min :: Ord a => a -> a -> a
on min(x, y)
if y < x then
y
else
x
end if
end min
-- 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
-- unlines :: [String] -> String
on unlines(xs)
intercalate(linefeed, xs)
end unlines
-- zip :: [a] -> [b] -> [(a, b)]
on zip(xs, ys)
set lng to min(length of xs, length of ys)
set lst to {}
repeat with i from 1 to lng
set end of lst to {item i of xs, item i of ys}
end repeat
return lst
end zip |
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
| #CoffeeScript | CoffeeScript |
I = (P) ->
# The cryptic name "I" follows the problem description;
# it returns a function that computes a moving average
# of successive values over the period P, using closure
# variables to maintain state.
cq = circular_queue(P)
num_elems = 0
sum = 0
SMA = (n) ->
sum += n
if num_elems < P
cq.add(n)
num_elems += 1
sum / num_elems
else
old = cq.replace(n)
sum -= old
sum / P
circular_queue = (n) ->
# queue that only ever stores up to n values;
# Caller shouldn't call replace until n values
# have been added.
i = 0
arr = []
add: (elem) ->
arr.push elem
replace: (elem) ->
# return value whose age is "n"
old_val = arr[i]
arr[i] = elem
i = (i + 1) % n
old_val
# The output of the code below should convince you that
# calling I multiple times returns functions with independent
# state.
sma3 = I(3)
sma7 = I(7)
sma11 = I(11)
for i in [1..10]
console.log i, sma3(i), sma7(i), sma11(i)
|
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
| #Julia | Julia | function barnsleyfern(n::Integer)
funs = (
(x, y) -> (0, 0.16y),
(x, y) -> (0.85x + 0.04y, -0.04x + 0.85y + 1.6),
(x, y) -> (0.2x - 0.26y, 0.23x + 0.22y + 1.6),
(x, y) -> (-0.15x + 0,28y, 0.26x + 0.24y + 0.44))
rst = Matrix{Float64}(n, 2)
rst[1, :] = 0.0
for row in 2:n
r = rand(0:99)
if r < 1; f = 1;
elseif r < 86; f = 2;
elseif r < 93; f = 3;
else f = 4; end
rst[row, 1], rst[row, 2] = funs[f](rst[row-1, 1], rst[row-1, 2])
end
return rst
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
| #OCaml | OCaml | let rms a =
sqrt (Array.fold_left (fun s x -> s +. x*.x) 0.0 a /.
float_of_int (Array.length a))
;;
rms (Array.init 10 (fun i -> float_of_int (i+1))) ;;
(* 6.2048368229954285 *) |
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
| #Oforth | Oforth | 10 seq map(#sq) sum 10.0 / 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.
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program babbage.s */
/************************************/
/* Constantes */
/************************************/
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/*********************************/
/* Initialized data */
/*********************************/
.data
sMessResult: .ascii "Result = "
sMessValeur: .fill 11, 1, ' ' @ size => 11
szCarriageReturn: .asciz "\n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
ldr r4,iNbStart @ start number = 269696
mov r5,#0 @ counter multiply
ldr r2,iNbMult @ value multiply = 1 000 000
mov r6,r4
1:
mov r0,r6
bl squareRoot @ compute square root
umull r1,r3,r0,r0
cmp r3,#0 @ overflow ?
bne 100f @ yes -> end
cmp r1,r6 @ perfect square
bne 2f @ no -> loop
ldr r1,iAdrsMessValeur
bl conversion10 @ call conversion decimal
ldr r0,iAdrsMessResult
bl affichageMess @ display message
b 100f @ end
2:
add r5,#1 @ increment counter
mul r3,r5,r2 @ multiply by 1 000 000
add r6,r3,r4 @ add start number
b 1b
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrsMessValeur: .int sMessValeur
iAdrszCarriageReturn: .int szCarriageReturn
iAdrsMessResult: .int sMessResult
iNbStart: .int 269696
iNbMult: .int 1000000
/******************************************************************/
/* compute squareRoot */
/******************************************************************/
/* r0 contains n */
/* r0 return result or -1 */
squareRoot:
push {r1-r5,lr} @ save registers
cmp r0,#0
beq 100f @ if zero -> end
movlt r0,#-1 @ if negatif return - 1
blt 100f
cmp r0,#4 @ if < 4 return 1
movlt r0,#1
blt 100f
@ start
clz r2,r0 @ number of zeros on the left
rsb r2,#32 @ so many useful numbers right
bic r2,#1 @ to have an even number of digits
mov r3,#0b11 @ mask for extract 2 bits
lsl r3,r2
mov r1,#0 @ init résult with 0
mov r4,#0 @ raz remainder area
1: @ begin loop
and r5,r0,r3 @ extract 2 bits with mask
add r4,r5,lsr r2 @ shift right and addition with remainder
lsl r5,r1,#1 @ multiplication by 2
lsl r5,#1 @ shift left one bit
orr r5,#1 @ bit right = 1
lsl r1,#1 @ shift left one bit
subs r4,r5 @ sub remainder
addmi r4,r4,r5 @ if negative restaur register
addpl r1,#1 @ else add 1
subs r2,#2 @ decrement number bits
movmi r0,r1 @ if end return result
bmi 100f
lsl r4,#2 @ no -> shift left remainder 2 bits
lsr r3,#2 @ and shift right mask 2 bits
b 1b @ and loop
100:
pop {r1-r5,lr} @ restaur registers
bx lr @return
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registres
mov r2,#0 @ counter length
1: @ loop length calculation
ldrb r1,[r0,r2] @ read octet start position + index
cmp r1,#0 @ if 0 its over
addne r2,r2,#1 @ else add 1 in the length
bne 1b @ and loop
@ so here r2 contains the length of the message
mov r1,r0 @ address message in r1
mov r0,#STDOUT @ code to write to the standard output Linux
mov r7, #WRITE @ code call system "write"
svc #0 @ call systeme
pop {r0,r1,r2,r7,lr} @ restaur des 2 registres */
bx lr @ return
/******************************************************************/
/* Converting a register to a decimal unsigned */
/******************************************************************/
/* r0 contains value and r1 address area */
/* r0 return size of result (no zero final in area) */
/* area size => 11 bytes */
.equ LGZONECAL, 10
conversion10:
push {r1-r4,lr} @ save registers
mov r3,r1
mov r2,#LGZONECAL
1: @ start loop
bl divisionpar10U @ unsigned r0 <- dividende. quotient ->r0 reste -> r1
add r1,#48 @ digit
strb r1,[r3,r2] @ store digit on area
cmp r0,#0 @ stop if quotient = 0
subne r2,#1 @ else previous position
bne 1b @ and loop
@ and move digit from left of area
mov r4,#0
2:
ldrb r1,[r3,r2]
strb r1,[r3,r4]
add r2,#1
add r4,#1
cmp r2,#LGZONECAL
ble 2b
@ and move spaces in end on area
mov r0,r4 @ result length
mov r1,#' ' @ space
3:
strb r1,[r3,r4] @ store space in area
add r4,#1 @ next position
cmp r4,#LGZONECAL
ble 3b @ loop if r4 <= area size
100:
pop {r1-r4,lr} @ restaur registres
bx lr @return
/***************************************************/
/* division par 10 unsigned */
/***************************************************/
/* r0 dividende */
/* r0 quotient */
/* r1 remainder */
divisionpar10U:
push {r2,r3,r4, lr}
mov r4,r0 @ save value
ldr r3,iMagicNumber @ r3 <- magic_number raspberry 1 2
umull r1, r2, r3, r0 @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0)
mov r0, r2, LSR #3 @ r2 <- r2 >> shift 3
add r2,r0,r0, lsl #2 @ r2 <- r0 * 5
sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10)
pop {r2,r3,r4,lr}
bx lr @ leave function
iMagicNumber: .int 0xCCCCCCCD
|
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
| #Common_Lisp | Common Lisp | (defun simple-moving-average (period &aux
(sum 0) (count 0) (values (make-list period)) (pointer values))
(setf (rest (last values)) values) ; construct circularity
(lambda (n)
(when (first pointer)
(decf sum (first pointer))) ; subtract old value
(incf sum n) ; add new value
(incf count)
(setf (first pointer) n)
(setf pointer (rest pointer)) ; advance pointer
(/ sum (min count period)))) |
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
| #Kotlin | Kotlin | // version 1.1.0
import java.awt.*
import java.awt.image.BufferedImage
import javax.swing.*
class BarnsleyFern(private val dim: Int) : JPanel() {
private val img: BufferedImage
init {
preferredSize = Dimension(dim, dim)
background = Color.black
img = BufferedImage(dim, dim, BufferedImage.TYPE_INT_ARGB)
createFern(dim, dim)
}
private fun createFern(w: Int, h: Int) {
var x = 0.0
var y = 0.0
for (i in 0 until 200_000) {
var tmpx: Double
var tmpy: Double
val r = Math.random()
if (r <= 0.01) {
tmpx = 0.0
tmpy = 0.16 * y
}
else if (r <= 0.86) {
tmpx = 0.85 * x + 0.04 * y
tmpy = -0.04 * x + 0.85 * y + 1.6
}
else if (r <= 0.93) {
tmpx = 0.2 * x - 0.26 * y
tmpy = 0.23 * x + 0.22 * y + 1.6
}
else {
tmpx = -0.15 * x + 0.28 * y
tmpy = 0.26 * x + 0.24 * y + 0.44
}
x = tmpx
y = tmpy
img.setRGB(Math.round(w / 2.0 + x * w / 11.0).toInt(),
Math.round(h - y * h / 11.0).toInt(), 0xFF32CD32.toInt())
}
}
override protected fun paintComponent(gg: Graphics) {
super.paintComponent(gg)
val g = gg as Graphics2D
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
g.drawImage(img, 0, 0, null)
}
}
fun main(args: Array<String>) {
SwingUtilities.invokeLater {
val f = JFrame()
f.defaultCloseOperation = JFrame.EXIT_ON_CLOSE
f.title = "Barnsley Fern"
f.setResizable(false)
f.add(BarnsleyFern(640), BorderLayout.CENTER)
f.pack()
f.setLocationRelativeTo(null)
f.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
| #ooRexx | ooRexx | call testAverage .array~of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
call testAverage .array~of(10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11)
call testAverage .array~of(30, 10, 20, 30, 40, 50, -100, 4.7, -11e2)
::routine testAverage
use arg list
say "list =" list~toString("l", ", ")
say "root mean square =" rootmeansquare(list)
say
::routine rootmeansquare
use arg numbers
-- return zero for an empty list
if numbers~isempty then return 0
sum = 0
do number over numbers
sum += number * number
end
return rxcalcsqrt(sum/numbers~items)
::requires rxmath LIBRARY |
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
| #Oz | Oz | declare
fun {Square X} X*X end
fun {RMS Xs}
{Sqrt
{Int.toFloat {FoldL {Map Xs Square} Number.'+' 0}}
/
{Int.toFloat {Length Xs}}}
end
in
{Show {RMS {List.number 1 10 1}}} |
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.
| #Arturo | Arturo | n: new 0
while [269696 <> (n^2) % 1000000]
-> inc 'n
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
| #Crystal | Crystal | def sma(n) Proc(Float64, Float64)
a = Array(Float64).new
->(x : Float64) {
a.shift if a.size == n
a.push x
a.sum / a.size.to_f
}
end
sma3, sma5 = sma(3), sma(5)
# Copied from the Ruby solution.
(1.upto(5).to_a + 5.downto(1).to_a).each do |n|
printf "%d: sma3 = %.3f - sma5 = %.3f\n", n, sma3.call(n.to_f), sma5.call(n.to_f)
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
| #Lambdatalk | Lambdatalk |
{def fern
{lambda {:size :sign}
{if {> :size 2}
then M:size
T{* 70 :sign}
{fern {* :size 0.5} {- :sign}}
T{* {- 70} :sign}
M:size
T{* {- 70} :sign}
{fern {* :size 0.5} :sign}
T{* 70 :sign}
T{* 7 :sign}
{fern {- :size 1} :sign}
T{* {- 7} :sign}
M{* -:size 2}
else }}}
{def F {fern 25 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
| #PARI.2FGP | PARI/GP | RMS(v)={
sqrt(sum(i=1,#v,v[i]^2)/#v)
};
RMS(vector(10,i,i)) |
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
| #Perl | Perl | use v5.10.0;
sub rms
{
my $r = 0;
$r += $_**2 for @_;
sqrt( $r/@_ );
}
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.
| #AutoHotkey | AutoHotkey |
; Give n an initial value
n = 519
; Loop this action while condition is not satisfied
while (Mod(n*n, 1000000) != 269696) {
; Increment n
n++
}
; Display n as value
msgbox, %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
| #D | D | import std.stdio, std.traits, std.algorithm;
auto sma(T, int period)() pure nothrow @safe {
T[period] data = 0;
T sum = 0;
int index, nFilled;
return (in T v) nothrow @safe @nogc {
sum += -data[index] + v;
data[index] = v;
index = (index + 1) % period;
nFilled = min(period, nFilled + 1);
return CommonType!(T, float)(sum) / nFilled;
};
}
void main() {
immutable s3 = sma!(int, 3);
immutable s5 = sma!(double, 5);
foreach (immutable e; [1, 2, 3, 4, 5, 5, 4, 3, 2, 1])
writefln("Added %d, sma(3) = %f, sma(5) = %f", e, s3(e), s5(e));
} |
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
| #Liberty_BASIC | Liberty BASIC | nomainwin
WindowWidth=800
WindowHeight=600
open "Barnsley Fern" for graphics_nf_nsb as #1
#1 "trapclose [q];down;fill black;flush;color green"
for n = 1 To WindowHeight * 50
r = int(rnd(1)*100)
Select Case
Case (r>=0) and (r<=84)
xn=0.85*x+0.04*y
yn=-0.04*x+0.85*y+1.6
Case (r>84) and (r<=91)
xn=0.2*x-0.26*y
yn=0.23*x+0.22*y+1.6
Case (r>91) and (r<=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
#1 "set ";x*80+300;" ";WindowHeight/1.1-y*50
next n
#1 "flush"
wait
[q]
close #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
| #Phix | Phix | function rms(sequence s)
atom sqsum = 0
for i=1 to length(s) do
sqsum += power(s[i],2)
end for
return sqrt(sqsum/length(s))
end function
?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
| #Phixmonti | Phixmonti | def rms
0 swap
len for
get 2 power rot + swap
endfor
len rot swap / sqrt
enddef
0 tolist
10 for
0 put
endfor
rms print |
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.
| #AWK | AWK |
# A comment starts with a "#" and are ignored by the machine. They can be on a
# line by themselves or at the end of an executable line.
#
# A program consists of multiple lines or statements. This program tests
# positive integers starting at 1 and terminates when one is found whose square
# ends in 269696.
#
# The next line shows how to run the program.
# syntax: GAWK -f BABBAGE_PROBLEM.AWK
#
BEGIN { # start of program
# this declares a variable named "n" and assigns it a value of zero
n = 0
# do what's inside the "{}" until n times n ends in 269696
do {
n = n + 1 # add 1 to n
} while (n*n !~ /269696$/)
# print the answer
print("The smallest number whose square ends in 269696 is " n)
print("Its square is " n*n)
# terminate program
exit(0)
} # end of program
|
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
| #Delphi | Delphi |
program Simple_moving_average;
{$APPTYPE CONSOLE}
type
TMovingAverage = record
private
buffer: TArray<Double>;
head: Integer;
Capacity: Integer;
Count: Integer;
sum, fValue: Double;
public
constructor Create(aCapacity: Integer);
function Add(Value: Double): Double;
procedure Reset;
property Value: Double read fValue;
end;
{ TMovingAverage }
function TMovingAverage.Add(Value: Double): Double;
begin
head := (head + 1) mod Capacity;
sum := sum + Value - buffer[head];
buffer[head] := Value;
if count < capacity then
begin
inc(Count);
fValue := sum / count;
exit(fValue);
end;
fValue := sum / Capacity;
Result := fValue;
end;
constructor TMovingAverage.Create(aCapacity: Integer);
begin
Capacity := aCapacity;
SetLength(buffer, aCapacity);
Reset;
end;
procedure TMovingAverage.Reset;
var
i: integer;
begin
head := -1;
Count := 0;
sum := 0;
fValue := 0;
for i := 0 to High(buffer) do
buffer[i] := 0;
end;
var
avg3, avg5: TMovingAverage;
i: Integer;
begin
avg3 := TMovingAverage.Create(3);
avg5 := TMovingAverage.Create(5);
for i := 1 to 5 do
begin
write('Inserting ', i, ' into avg3 ', avg3.Add(i): 0: 4);
writeln(' Inserting ', i, ' into avg5 ', avg5.Add(i): 0: 4);
end;
for i := 5 downto 1 do
begin
write('Inserting ', i, ' into avg3 ', avg3.Add(i): 0: 4);
writeln(' Inserting ', i, ' into avg5 ', avg5.Add(i): 0: 4);
end;
avg3.Reset;
for i := 1 to 100000000 do
avg3.Add(i);
writeln('100''000''000 insertions ', avg3.Value: 0: 4);
Readln;
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
| #Locomotive_Basic | Locomotive Basic | 10 mode 2:ink 0,0:ink 1,18:randomize time
20 scale=38
30 maxpoints=20000: x=0: y=0
40 for z=1 to maxpoints
50 p=rnd*100
60 if p<=1 then nx=0: ny=0.16*y: goto 100
70 if p<=8 then nx=0.2*x-0.26*y: ny=0.23*x+0.22*y+1.6: goto 100
80 if p<=15 then nx=-0.15*x+0.28*y: ny=0.26*x+0.24*y+0.44: goto 100
90 nx=0.85*x+0.04*y: ny=-0.04*x+0.85*y+1.6
100 x=nx: y=ny
110 plot scale*x+320,scale*y
120 next |
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
| #PHP | PHP | <?php
// Created with PHP 7.0
function rms(array $numbers)
{
$sum = 0;
foreach ($numbers as $number) {
$sum += $number**2;
}
return sqrt($sum / count($numbers));
}
echo rms(array(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
| #Picat | Picat |
rms(Xs) = Y =>
Sum = sum_of_squares(Xs),
N = length(Xs),
Y = sqrt(Sum / N).
sum_of_squares(Xs) = Sum =>
Sum = 0,
foreach (X in Xs)
Sum := Sum + X * X
end.
main =>
Y = rms(1..10),
printf("The root-mean-square of 1..10 is %f\n", Y).
|
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.
| #BASIC | BASIC |
100 :
110 REM BABBAGE PROBLEM
120 :
130 DEF FN ST(A) = N - INT (A) * INT (A)
140 N = 269696
150 N = N + 1000000
160 R = SQR (N)
170 IF FN ST(R) < > 0 AND N < 999999999 THEN GOTO 150
180 IF N > 999999999 THEN GOTO 210
190 PRINT "SMALLESt NUMBER WHOSE
SQUARE ENDS IN"; CHR$ (13);
"269696 IS ";R;", AND THE
SQUARE IS"; CHR$ (13);N
200 END
210 PRINT "THERE IS NO SOLUTION
FOR VALUES SMALLER"; CHR$(13);
"THAN 999999999."
|
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
| #Dyalect | Dyalect | func avg(xs) {
var acc = 0.0
var c = 0
for x in xs {
c += 1
acc += x
}
acc / c
}
func sma(p) {
var s = []
x => {
if s.Length() >= p {
s.RemoveAt(0)
}
s.Insert(s.Length(), x)
avg(s)
};
}
var nums = Iterator.Concat(1.0..5.0, 5.0^-1.0..1.0)
var sma3 = sma(3)
var sma5 = sma(5)
for n in nums {
print("\(n)\t(sma3) \(sma3(n))\t(sma5) \(sma5(n))")
} |
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
| #Lua | Lua |
g = love.graphics
wid, hei = g.getWidth(), g.getHeight()
function choose( i, j )
local r = math.random()
if r < .01 then return 0, .16 * j
elseif r < .07 then return .2 * i - .26 * j, .23 * i + .22 * j + 1.6
elseif r < .14 then return -.15 * i + .28 * j, .26 * i + .24 * j + .44
else return .85 * i + .04 * j, -.04 * i + .85 * j + 1.6
end
end
function createFern( iterations )
local hw, x, y, scale = wid / 2, 0, 0, 45
local pts = {}
for k = 1, iterations do
pts[1] = { hw + x * scale, hei - 15 - y * scale,
20 + math.random( 80 ),
128 + math.random( 128 ),
20 + math.random( 80 ), 150 }
g.points( pts )
x, y = choose( x, y )
end
end
function love.load()
math.randomseed( os.time() )
canvas = g.newCanvas( wid, hei )
g.setCanvas( canvas )
createFern( 15e4 )
g.setCanvas()
end
function love.draw()
g.draw( canvas )
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
| #PicoLisp | PicoLisp | (scl 5)
(let Lst (1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0)
(prinl
(format
(sqrt
(*/
(sum '((N) (*/ N N 1.0)) Lst)
1.0
(length Lst) )
T )
*Scl ) ) ) |
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
| #PL.2FI | PL/I | atest: Proc Options(main);
declare A(10) Dec Float(15) static initial (1,2,3,4,5,6,7,8,9,10);
declare (n,RMS) Dec Float(15);
n = hbound(A,1);
RMS = sqrt(sum(A**2)/n);
put Skip Data(rms);
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.
| #Batch_File | Batch File |
:: This line is only required to increase the readability of the output by hiding the lines of code being executed
@echo off
:: Everything between the lines keeps repeating until the answer is found
:: The code works by, starting at 1, checking to see if the last 6 digits of the current number squared is equal to 269696
::----------------------------------------------------------------------------------
:loop
:: Increment the current number being tested by 1
set /a number+=1
:: Square the current number
set /a numbersquared=%number%*%number%
:: Check if the last 6 digits of the current number squared is equal to 269696, and if so, stop looping and go to the end
if %numbersquared:~-6%==269696 goto end
goto loop
::----------------------------------------------------------------------------------
:end
echo %number% * %number% = %numbersquared%
pause>nul
|
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
| #E | E | pragma.enable("accumulator")
def makeMovingAverage(period) {
def values := ([null] * period).diverge()
var index := 0
var count := 0
def insert(v) {
values[index] := v
index := (index + 1) %% period
count += 1
}
/** Returns the simple moving average of the inputs so far, or null if there
have been no inputs. */
def average() {
if (count > 0) {
return accum 0 for x :notNull in values { _ + x } / count.min(period)
}
}
return [insert, average]
} |
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
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language |
BarnsleyFern[{x_, y_}] := Module[{},
i = RandomInteger[{1, 100}];
If[i <= 1, {xt = 0, yt = 0.16*y},
If[i <= 8, {xt = 0.2*x - 0.26*y, yt = 0.23*x + 0.22*y + 1.6},
If[i <= 15, {xt = -0.15*x + 0.28*y, yt = 0.26*x + 0.24*y + 0.44},
{xt = 0.85*x + 0.04*y, yt = -0.04*x + 0.85*y + 1.6}]]];
{xt, yt}];
points = NestList[BarnsleyFern, {0,0}, 100000];
Show[Graphics[{Hue[.35, 1, .7], PointSize[.001], Point[#] & /@ points}]]
|
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
| #PostScript | PostScript | /findrms{
/x exch def
/sum 0 def
/i 0 def
x length 0 eq{}
{
x length{
/sum x i get 2 exp sum add def
/i i 1 add def
}repeat
/sum sum x length div sqrt def
}ifelse
sum ==
}def
[1 2 3 4 5 6 7 8 9 10] findrms |
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
| #Potion | Potion | rms = (series) :
total = 0.0
series each (x): total += x * x.
total /= series length
total sqrt
.
rms((1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) print |
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.
| #Befunge | Befunge | 1+ ::* "d"::** % "V8":** -! #v_ > > > > >
v
increment n n*n modulo 1000000 equal to 269696? v if false, loop to right
v
v"Smallest number whose square ends in 269696 is "0 < else output n below
>:#,_$ . 55+, @
ouput message then n newline exit
numeric constants explained:
"d" ascii value of 'd', i.e. 100
:: duplicate twice: 100,100,100
** multiply twice: 100*100*100 = 1000000
"V8" ascii values of 'V' and '8', i.e. 86 and 56
: duplicate the '8' (56): 86,56,56
** multiply twice: 86*56*56 = 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
| #EchoLisp | EchoLisp |
(lib 'tree) ;; queues operations
(define (make-sma p)
(define Q (queue (gensym)))
(lambda (item)
(q-push Q item)
(when (> (queue-length Q) p) (q-pop Q))
(// (for/sum ((x (queue->list Q))) x) (queue-length Q))))
|
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
| #MiniScript | MiniScript | clear
x = 0
y = 0
for i in range(100000)
gfx.setPixel 300 + 58 * x, 58 * y, color.green
roll = rnd * 100
xp = x
if roll < 1 then
x = 0
y = 0.16 * y
else if roll < 86 then
x = 0.85 * x + 0.04 * y
y = -0.04 * xp + 0.85 * y + 1.6
else if roll < 93 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 if
end for |
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
| #Powerbuilder | Powerbuilder | long ll_x, ll_y, ll_product
decimal ld_rms
ll_x = 1
ll_y = 10
DO WHILE ll_x <= ll_y
ll_product += ll_x * ll_x
ll_x ++
LOOP
ld_rms = Sqrt(ll_product / ll_y)
//ld_rms value is 6.20483682299542849 |
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
| #PowerShell | PowerShell | function get-rms([float[]]$nums){
$sqsum=$nums | foreach-object { $_*$_} | measure-object -sum | select-object -expand Sum
return [math]::sqrt($sqsum/$nums.count)
}
get-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.
| #Bracmat | Bracmat |
(
500:?number {A child knows that 269696 is larger than 500*500,
but not by much. It is safe to start the search with 500.}
& whl {'whl' is shorthand for 'while'. It announces the evaluation of
an expression that is repeated until it fails.}
' ( @(!number*!number:~(? 269696)) { ~(? 269696) is a pattern. It says
that it will not match numbers that do
not end with the figures 269696.
The question mark is there to match all
the figures before 269696.}
& !number:<99736 { We should under no circumstance try
numbers that are larger than 99736.}
& 1+!number:?number { If the number did not pass the test,
we take the next number and repeat
the test. }
)
& out
$ ( str
$ ( "The smallest number that ends with the figures 269696 when squared is "
!number
", since the square of "
!number
" is "
!number*!number
)
)
)
|
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
| #Elena | Elena | import system'routines;
import system'collections;
import extensions;
class SMA
{
object thePeriod;
object theList;
constructor new(period)
{
thePeriod := period;
theList :=new List();
}
append(n)
{
theList.append(n);
var count := theList.Length;
count =>
0 { ^0.0r }
: {
if (count > thePeriod)
{
theList.removeAt:0;
count := thePeriod
};
var sum := theList.summarize(Real.new());
^ sum / count
}
}
}
public program()
{
var SMA3 := SMA.new:3;
var SMA5 := SMA.new:5;
for (int i := 1, i <= 5, i += 1) {
console.printPaddingRight(30, "sma3 + ", i, " = ", SMA3.append:i);
console.printLine("sma5 + ", i, " = ", SMA5.append:i)
};
for (int i := 5, i >= 1, i -= 1) {
console.printPaddingRight(30, "sma3 + ", i, " = ", SMA3.append:i);
console.printLine("sma5 + ", i, " = ", SMA5.append:i)
};
console.readChar()
} |
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
| #Nim | Nim |
import nimPNG, random
randomize()
const
width = 640
height = 640
minX = -2.1815
maxX = 2.6556
minY = 0.0
maxY = 9.9982
iterations = 1_000_000
var img: array[width * height * 3, char]
proc floatToPixel(x,y:float): tuple[a:int,b:int] =
var px = abs(x - minX) / abs(maxX - minX)
var py = abs(y - minY) / abs(maxY - minY)
var a:int = (int)(width * px)
var b:int = (int)(height * py)
a = a.clamp(0, width-1)
b = b.clamp(0, height-1)
# flip the y axis
(a:a,b:height-b-1)
proc pixelToOffset(a,b: int): int =
b * width * 3 + a * 3
proc toString(a: openArray[char]): string =
result = newStringOfCap(a.len)
for ch in items(a):
result.add(ch)
proc drawPixel(x,y:float) =
var (a,b) = floatToPixel(x,y)
var offset = pixelToOffset(a,b)
#img[offset] = 0 # red channel
img[offset+1] = char(250) # green channel
#img[offset+2] = 0 # blue channel
# main
var x, y: float = 0.0
for i in 1..iterations:
var r = random(101)
var nx, ny: float
if r <= 85:
nx = 0.85 * x + 0.04 * y
ny = -0.04 * x + 0.85 * y + 1.6
elif r <= 85 + 7:
nx = 0.2 * x - 0.26 * y
ny = 0.23 * x + 0.22 * y + 1.6
elif r <= 85 + 7 + 7:
nx = -0.15 * x + 0.28 * y
ny = 0.26 * x + 0.24 * y + 0.44
else:
nx = 0
ny = 0.16 * y
x = nx
y = ny
drawPixel(x,y)
discard savePNG24("fern.png",img.toString, width, height)
|
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
| #Oberon-2 | Oberon-2 |
MODULE BarnsleyFern;
(**
Oxford Oberon-2
**)
IMPORT Random, XYplane;
VAR
a1, b1, c1, d1, e1, f1, p1: REAL;
a2, b2, c2, d2, e2, f2, p2: REAL;
a3, b3, c3, d3, e3, f3, p3: REAL;
a4, b4, c4, d4, e4, f4, p4: REAL;
X, Y: REAL;
x0, y0, e: INTEGER;
PROCEDURE Draw;
VAR x, y: REAL; xi, eta: INTEGER; rn: REAL;
BEGIN
REPEAT
rn := Random.Uniform();
IF rn < p1 THEN
x := a1 * X + b1 * Y + e1; y := c1 * X + d1 * Y + f1
ELSIF rn < (p1 + p2) THEN
x := a2 *X + b2 * Y + e2; y := c2 * X + d2 * Y + f2
ELSIF rn < (p1 + p2 + p3) THEN
x := a3 * X + b3 * Y + e3; y := c3 * X + d3 * Y + f3
ELSE
x := a4 * X + b4 * Y + e4; y := c4 * X + d4 * Y + f4
END;
X := x; xi := x0 + SHORT(ENTIER(X * e));
Y := y; eta := y0 + SHORT(ENTIER(Y * e));
XYplane.Dot(xi, eta, XYplane.draw)
UNTIL "s" = XYplane.Key()
END Draw;
PROCEDURE Init;
BEGIN
X := 0; Y := 0;
x0 := 120; y0 := 0; e := 25;
a1 := 0.00; a2 := 0.85; a3 := 0.20; a4 := -0.15;
b1 := 0.00; b2 := 0.04; b3 := -0.26; b4 := 0.28;
c1 := 0.00; c2 := -0.04; c3 := 0.23; c4 := 0.26;
d1 := 0.16; d2 := 0.85; d3 := 0.22; d4 := 0.24;
e1 := 0.00; e2 := 0.00; e3 := 0.00; e4 := 0.00;
f1 := 0.00; f2 := 1.60; f3 := 1.60; f4 := 0.44;
p1 := 0.01; p2 := 0.85; p3 := 0.07; p4 := 0.07;
XYplane.Open;
END Init;
BEGIN
Init;Draw
END BarnsleyFern.
|
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
| #Processing | Processing | void setup() {
float[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
print(rms(numbers));
}
float rms(float[] nums) {
float mean = 0;
for (float n : nums) {
mean += sq(n);
}
mean = sqrt(mean / nums.length);
return mean;
} |
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
| #Prolog | Prolog |
:- initialization(main).
rms(Xs, Y) :-
sum_of_squares(Xs, 0, Sum),
length(Xs, N),
Y is sqrt(Sum / N).
sum_of_squares([], Sum, Sum).
sum_of_squares([X|Xs], A, Sum) :-
A1 is A + X * X,
sum_of_squares(Xs, A1, Sum).
main :-
bagof(X, between(1, 10, X), Xs),
rms(Xs, Y),
format('The root-mean-square of 1..10 is ~f\n', [Y]).
|
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.
| #C | C |
// This code is the implementation of Babbage Problem
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
int main() {
int current = 0, //the current number
square; //the square of the current number
//the strategy of take the rest of division by 1e06 is
//to take the a number how 6 last digits are 269696
while (((square=current*current) % 1000000 != 269696) && (square<INT_MAX)) {
current++;
}
//output
if (square>+INT_MAX)
printf("Condition not satisfied before INT_MAX reached.");
else
printf ("The smallest number whose square ends in 269696 is %d\n", current);
//the end
return 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
| #Elixir | Elixir | $ cat simple-moving-avg.exs
#!/usr/bin/env elixir
defmodule Math do
def average([]), do: nil
def average(enum) do
Enum.sum(enum) / length(enum)
end
end
defmodule SMA do
def sma(l, p \\ 10) do
IO.puts("\nSimple moving average(period=#{p}):")
Enum.chunk(l, p, 1)
|> Enum.map(&(%{"input": &1, "avg": Float.round(Math.average(&1), 3)}))
end
defmacro gen_func(p) do
quote do
fn l -> SMA.sma(l, unquote(p)) end
end
end
def read_numeric_input do
IO.stream(:stdio, :line)
|> Enum.map(&(String.split(&1, ~r{\s+})))
|> List.flatten()
|> Enum.reject(&(is_nil(&1) || String.length(&1) == 0))
|> Enum.map(&(Integer.parse(&1) |> elem(0)))
end
def run do
sma_func_10 = gen_func(10)
sma_func_15 = gen_func(15)
numbers = read_numeric_input
sma_func_10.(numbers) |> IO.inspect
sma_func_15.(numbers) |> IO.inspect
end
end
SMA.run |
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
| #PARI.2FGP | PARI/GP |
\\ Barnsley fern fractal
\\ 6/17/16 aev
pBarnsleyFern(size,lim)={
my(X=List(),Y=X,x=y=xw=yw=0.0,r);
print(" *** Barnsley Fern, size=",size," lim=",lim);
plotinit(0); plotcolor(0,6); \\green
plotscale(0, -3,3, 0,10); plotmove(0, 0,0);
for(i=1, lim,
r=random(100);
if(r<=1, xw=0;yw=0.16*y,
if(r<=8, xw=0.2*x-0.26*y;yw=0.23*x+0.22*y+1.6,
if(r<=15, xw=-0.15*x+0.28*y;yw=0.26*x+0.24*y+0.44,
xw=0.85*x+0.04*y;yw=-0.04*x+0.85*y+1.6)));
x=xw;y=yw; listput(X,x); listput(Y,y);
);\\fend i
plotpoints(0,Vec(X),Vec(Y));
plotdraw([0,-3,-0]);
}
{\\ Executing:
pBarnsleyFern(530,100000); \\ 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
| #PureBasic | PureBasic | NewList MyList() ; To hold a unknown amount of numbers to calculate
If OpenConsole()
Define.d result
Define i, sum_of_squares
;Populate a random amounts of numbers to calculate
For i=0 To (Random(45)+5) ; max elements is unknown to the program
AddElement(MyList())
MyList()=Random(15) ; Put in a random number
Next
Print("Averages/Root mean square"+#CRLF$+"of : ")
; Calculate square of each element, print each & add them together
ForEach MyList()
Print(Str(MyList())+" ") ; Present to our user
sum_of_squares+MyList()*MyList() ; Sum the squares, e.g
Next
;Present the result
result=Sqr(sum_of_squares/ListSize(MyList()))
PrintN(#CRLF$+"= "+StrD(result))
PrintN("Press ENTER to exit"): Input()
CloseConsole()
EndIf |
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.
| #C.23 | C# | namespace Babbage_Problem
{
class iterateNumbers
{
public iterateNumbers()
{
long baseNumberSquared = 0; //the base number multiplied by itself
long baseNumber = 0; //the number to be squared, this one will be iterated
do //this sets up the loop
{
baseNumber += 1; //add one to the base number
baseNumberSquared = baseNumber * baseNumber; //multiply the base number by itself and store the value as baseNumberSquared
}
while (Right6Digits(baseNumberSquared) != 269696); //this will continue the loop until the right 6 digits of the base number squared are 269,696
Console.WriteLine("The smallest integer whose square ends in 269,696 is " + baseNumber);
Console.WriteLine("The square is " + baseNumberSquared);
}
private long Right6Digits(long baseNumberSquared)
{
string numberAsString = baseNumberSquared.ToString(); //this is converts the number to a different type so it can be cut up
if (numberAsString.Length < 6) { return baseNumberSquared; }; //if the number doesn't have 6 digits in it, just return it to try again.
numberAsString = numberAsString.Substring(numberAsString.Length - 6); //this extracts the last 6 digits from the number
return long.Parse(numberAsString); //return the last 6 digits of the number
}
}
}} |
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
| #Erlang | Erlang | main() ->
SMA3 = sma(3),
SMA5 = sma(5),
Ns = [1, 2, 3, 4, 5, 5, 4, 3, 2, 1],
lists:foreach(
fun (N) ->
io:format("Added ~b, sma(3) -> ~f, sma(5) -> ~f~n",[N,next(SMA3,N),next(SMA5,N)])
end, Ns),
stop(SMA3),
stop(SMA5).
sma(W) ->
{sma,spawn(?MODULE,loop,[W,[]])}.
loop(Window, Numbers) ->
receive
{_Pid, stop} ->
ok;
{Pid, N} when is_number(N) ->
case length(Numbers) < Window of
true ->
Next = Numbers++[N];
false ->
Next = tl(Numbers)++[N]
end,
Pid ! {average, lists:sum(Next)/length(Next)},
loop(Window,Next);
_ ->
ok
end.
stop({sma,Pid}) ->
Pid ! {self(),stop},
ok.
next({sma,Pid},N) ->
Pid ! {self(), N},
receive
{average, Ave} ->
Ave
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
| #Perl | Perl | use Imager;
my $w = 640;
my $h = 640;
my $img = Imager->new(xsize => $w, ysize => $h, channels => 3);
my $green = Imager::Color->new('#00FF00');
my ($x, $y) = (0, 0);
foreach (1 .. 2e5) {
my $r = rand(100);
($x, $y) = do {
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 + $x * 60, y => $y * 60, 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
| #Python | Python | >>> from math import sqrt
>>> def qmean(num):
return sqrt(sum(n*n for n in num)/len(num))
>>> qmean(range(1,11))
6.2048368229954285 |
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
| #Qi | Qi | (define rms
R -> (sqrt (/ (APPLY + (MAPCAR * R R)) (length R)))) |
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.
| #C.2B.2B | C++ | #include <iostream>
int main( ) {
int current = 0 ;
while ( ( current * current ) % 1000000 != 269696 )
current++ ;
std::cout << "The square of " << current << " is " << (current * current) << " !\n" ;
return 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
| #Euler_Math_Toolbox | Euler Math Toolbox |
>n=1000; m=100; x=random(1,n);
>x10=fold(x,ones(1,m)/m);
>x10=fftfold(x,ones(1,m)/m)[m:n]; // more efficient
|
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
| #Phix | Phix | --
-- pwa\phix\BarnsleyFern.exw
-- =========================
--
with javascript_semantics
include pGUI.e
Ihandle dlg, canvas
cdCanvas cddbuffer, cdcanvas
function redraw_cb(Ihandle /*canvas*/, integer /*posx*/, integer /*posy*/)
atom x = 0, y = 0
integer {width, height} = IupGetIntInt(canvas, "DRAWSIZE")
cdCanvasActivate(cddbuffer)
for i=1 to 100000 do
integer r = rand(100)
-- {x, y} = iff(r<=1? { 0, 0.16*y } :
-- iff(r<=8? { 0.20*x-0.26*y, 0.23*x+0.22*y+1.60} :
-- iff(r<=15?{-0.15*x+0.28*y, 0.26*x+0.24*y+0.44} :
-- { 0.85*x+0.04*y,-0.04*x+0.85*y+1.60})))
if r<=1 then {x, y} = { 0, 0.16*y }
elsif r<=8 then {x, y} = { 0.20*x-0.26*y, 0.23*x+0.22*y+1.60}
elsif r<=15 then {x, y} = {-0.15*x+0.28*y, 0.26*x+0.24*y+0.44}
else {x, y} = { 0.85*x+0.04*y,-0.04*x+0.85*y+1.60}
end if
cdCanvasPixel(cddbuffer, width/2+x*50, y*50, CD_DARK_GREEN)
end for
cdCanvasFlush(cddbuffer)
return IUP_DEFAULT
end function
IupOpen()
canvas = IupCanvas(Icallback("redraw_cb"),"RASTERSIZE=340x540")
dlg = IupDialog(canvas,`TITLE="Barnsley Fern"`)
IupMap(dlg)
cdcanvas = cdCreateCanvas(CD_IUP, canvas)
cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas)
IupSetAttribute(canvas, "RASTERSIZE", NULL) -- release the minimum limitation
IupShow(dlg)
if platform()!=JS then
IupMainLoop()
IupClose()
end if
|
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
| #Quackery | Quackery | [ $ "bigrat.qky" loadfile ] now!
[ [] swap
witheach
[ unpack 2dup v*
join nested join ] ] is squareall ( [ --> [ )
[ dup size n->v rot
0 n->v rot
witheach
[ unpack v+ ]
2swap v/ ] is arithmean ( [ --> n/d )
[ dip
[ squareall arithmean ]
vsqrt drop ] is rms ( [ n --> n/d )
say "The RMS of the integers 1 to 10, to 80 decimal places with rounding." cr
say "(Checked on Wolfram Alpha. The final digit is correctly rounded up.)" cr cr
' [ [ 1 1 ] [ 2 1 ] [ 3 1 ] [ 4 1 ] [ 5 1 ]
[ 6 1 ] [ 7 1 ] [ 8 1 ] [ 9 1 ] [ 10 1 ] ]
( ^^^ the integers 1 to 10 represented as a nest of nested rational numbers )
80 rms
80 point$ echo$ |
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
| #R | R | RMS <- function(x, na.rm = F) sqrt(mean(x^2, na.rm = na.rm))
RMS(1:10)
# [1] 6.204837
RMS(c(NA, 1:10))
# [1] NA
RMS(c(NA, 1:10), na.rm = T)
# [1] 6.204837 |
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.
| #Cach.C3.A9_ObjectScript | Caché ObjectScript | BABBAGE
; start at the integer prior to the square root of 269,696 as it has to be at least that big
set i = ($piece($zsqr(269696),".",1,1) - 1) ; piece 1 of . gets the integer portion
; loop forever, incrementing by one, until we find a square ending in 269696
for {
set i = i + 1 ; this will start us at the integer value from the piece statement above
; evaluate if the last 6 digits of the square equal 269696
set square = i * i
if ($extract(square,$length(square) - 5,$length(square)) = 269696) {
; We match - display the integer and square value to the screen, formatting the numerics with a comma separator as needed.
write !,"Result: "_$fnumber(i,",")_" squared is "_$fnumber(square,",")_". This ends in 269696."
quit ; exit for loop
}
}
quit ; exit routine |
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
| #F.23 | F# | let sma period f (list:float list) =
let sma_aux queue v =
let q = Seq.truncate period (v :: queue)
Seq.average q, Seq.toList q
List.fold (fun s v ->
let avg,state = sma_aux s v
f avg
state) [] list
printf "sma3: "
[ 1.;2.;3.;4.;5.;5.;4.;3.;2.;1.] |> sma 3 (printf "%.2f ")
printf "\nsma5: "
[ 1.;2.;3.;4.;5.;5.;4.;3.;2.;1.] |> sma 5 (printf "%.2f ")
printfn "" |
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
| #PicoLisp | PicoLisp | `(== 64 64)
(seed (in "/dev/urandom" (rd 8)))
(scl 20)
(de gridX (X)
(*/ (+ 320.0 (*/ X 58.18 1.0)) 1.0) )
(de gridY (Y)
(*/ (- 640.0 (*/ Y 58.18 1.0)) 1.0) )
(de calc (R X Y)
(cond
((< R 1) (list 0 (*/ Y 0.16 1.0)))
((< R 86)
(list
(+ (*/ 0.85 X 1.0) (*/ 0.04 Y 1.0))
(+ (*/ -0.04 X 1.0) (*/ 0.85 Y 1.0) 1.6) ) )
((< R 93)
(list
(- (*/ 0.2 X 1.0) (*/ 0.26 Y 1.0))
(+ (*/ 0.23 X 1.0) (*/ 0.22 Y 1.0) 1.6) ) )
(T
(list
(+ (*/ -0.15 X 1.0) (*/ 0.28 Y 1.0))
(+ (*/ 0.26 X 1.0) (*/ 0.24 Y 1.0) 0.44) ) ) ) )
(let
(X 0
Y 0
G (make (do 640 (link (need 640 0)))) )
(do 100000
(let ((A B) (calc (rand 0 99) X Y))
(setq X A Y B)
(set (nth G (gridY Y) (gridX X)) 1) ) )
(out "fern.pbm"
(prinl "P1")
(prinl 640 " " 640)
(mapc prinl G) ) ) |
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
| #Processing | Processing | void setup() {
size(640, 640);
background(0, 0, 0);
}
float x = 0;
float y = 0;
void draw() {
for (int i = 0; i < 100000; i++) {
float xt = 0;
float yt = 0;
float r = random(100);
if (r <= 1) {
xt = 0;
yt = 0.16*y;
} else if (r <= 8) {
xt = 0.20*x - 0.26*y;
yt = 0.23*x + 0.22*y + 1.60;
} else if (r <= 15) {
xt = -0.15*x + 0.28*y;
yt = 0.26*x + 0.24*y + 0.44;
} else {
xt = 0.85*x + 0.04*y;
yt = -0.04*x + 0.85*y + 1.60;
}
x = xt;
y = yt;
int m = round(width/2 + 60*x);
int n = height-round(60*y);
set(m, n, #00ff00);
}
noLoop();
} |
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
| #Racket | Racket |
#lang racket
(define (rms nums)
(sqrt (/ (for/sum ([n nums]) (* n n)) (length nums))))
|
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
| #Raku | Raku | sub rms(*@nums) { sqrt [+](@nums X** 2) / @nums }
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.
| #Clojure | Clojure | ; Defines function named babbage? that returns true if the
; square of the provided number leaves a remainder of 269,696 when divided
; by a million
(defn babbage? [n]
(let [square (* n n)]
(= 269696 (mod square 1000000))))
; Use the above babbage? to find the first positive integer that returns true
; (We're exploiting Clojure's laziness here; (range) with no parameters returns
; an infinite series.)
(first (filter babbage? (range))) |
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
| #Factor | Factor | USING: kernel interpolate io locals math.statistics prettyprint
random sequences ;
IN: rosetta-code.simple-moving-avg
:: I ( P -- quot )
V{ } clone :> v!
[ v swap suffix! P short tail* v! ] ;
: sma-add ( quot n -- quot' ) swap tuck call( x x -- x ) ;
: sma-query ( quot -- avg v ) first concat dup mean swap ;
: simple-moving-average-demo ( -- )
5 I 10 <iota> [
over sma-query unparse
[I After ${2} numbers Sequence is ${0} Mean is ${1}I] nl
100 random sma-add
] each drop ;
MAIN: simple-moving-average-demo |
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
| #PureBasic | PureBasic | EnableExplicit
DisableDebugger
DataSection
R84: : Data.d 0.85,0.04,-0.04,0.85,1.6
R91: : Data.d 0.2,-0.26,0.23,0.22,1.6
R98: : Data.d -0.15,0.28,0.26,0.24,0.44
R100: : Data.d 0.0,0.0,0.0,0.16,0.0
EndDataSection
Procedure Barnsley(height.i)
Define x.d, y.d, xn.d, yn.d, v1.d, v2.d, v3.d, v4.d, v5.d,
f.d=height/10.6,
offset.i=Int(height/4-height/40),
n.i, r.i
For n=1 To height*50
r=Random(99,0)
Select r
Case 0 To 84 : Restore R84
Case 85 To 91 : Restore R91
Case 92 To 98 : Restore R98
Default : Restore R100
EndSelect
Read.d v1 : Read.d v2 : Read.d v3 : Read.d v4 : Read.d v5
xn=v1*x+v2*y : yn=v3*x+v4*y+v5
x=xn : y=yn
Plot(offset+x*f,height-y*f,RGB(0,255,0))
Next
EndProcedure
Define w1.i=400,
h1.i=800
If OpenWindow(0,#PB_Ignore,#PB_Ignore,w1,h1,"Barnsley fern")
If CreateImage(0,w1,h1,24,0) And StartDrawing(ImageOutput(0))
Barnsley(h1)
StopDrawing()
EndIf
ImageGadget(0,0,0,0,0,ImageID(0))
Repeat : Until WaitWindowEvent(50)=#PB_Event_CloseWindow
EndIf
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
| #REXX | REXX | /*REXX program computes and displays the root mean square (RMS) of a number sequence. */
parse arg nums digs show . /*obtain the optional arguments from CL*/
if nums=='' | nums=="," then nums=10 /*Not specified? Then use the default.*/
if digs=='' | digs=="," then digs=50 /* " " " " " " */
if show=='' | show=="," then show=10 /* " " " " " " */
numeric digits digs /*uses DIGS decimal digits for calc. */
$=0; do j=1 for nums /*process each of the N integers. */
$=$ + j**2 /*sum the squares of the integers. */
end /*j*/
/* [↓] displays SHOW decimal digits.*/
rms=format( sqrt($/nums), , show ) / 1 /*divide by N, then calculate the SQRT.*/
say 'root mean square for 1──►'nums "is: " rms /*display the root mean square (RMS). */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); numeric digits; m.=9
numeric form; parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g *.5'e'_ % 2
h=d+6; do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/
do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/
return g |
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.
| #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. BABBAGE-PROGRAM.
* A line beginning with an asterisk is an explanatory note.
* The machine will disregard any such line.
DATA DIVISION.
WORKING-STORAGE SECTION.
* In this part of the program we reserve the storage space we shall
* be using for our variables, using a 'PICTURE' clause to specify
* how many digits the machine is to keep free.
* The prefixed number 77 indicates that these variables do not form part
* of any larger 'record' that we might want to deal with as a whole.
77 N PICTURE 99999.
* We know that 99,736 is a valid answer.
77 N-SQUARED PICTURE 9999999999.
77 LAST-SIX PICTURE 999999.
PROCEDURE DIVISION.
* Here we specify the calculations that the machine is to carry out.
CONTROL-PARAGRAPH.
PERFORM COMPUTATION-PARAGRAPH VARYING N FROM 1 BY 1
UNTIL LAST-SIX IS EQUAL TO 269696.
STOP RUN.
COMPUTATION-PARAGRAPH.
MULTIPLY N BY N GIVING N-SQUARED.
MOVE N-SQUARED TO LAST-SIX.
* Since the variable LAST-SIX can hold a maximum of six digits,
* only the final six digits of N-SQUARED will be moved into it:
* the rest will not fit and will simply be discarded.
IF LAST-SIX IS EQUAL TO 269696 THEN DISPLAY 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
| #Fantom | Fantom |
class MovingAverage
{
Int period
Int[] stream
new make (Int period)
{
this.period = period
stream = [,]
}
// add number to end of stream and remove numbers from start if
// stream is larger than period
public Void addNumber (Int number)
{
stream.add (number)
while (stream.size > period)
{
stream.removeAt (0)
}
}
// compute average of numbers in stream
public Float average ()
{
if (stream.isEmpty)
return 0.0f
else
1.0f * (Int)(stream.reduce(0, |a,b| { (Int) a + b })) / stream.size
}
}
class Main
{
public static Void main ()
{ // test by adding random numbers and printing average after each number
av := MovingAverage (5)
10.times |i|
{
echo ("After $i numbers list is ${av.stream} average is ${av.average}")
av.addNumber (Int.random(0..100))
}
}
}
|
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
| #Python | Python |
import random
from PIL import Image
class BarnsleyFern(object):
def __init__(self, img_width, img_height, paint_color=(0, 150, 0),
bg_color=(255, 255, 255)):
self.img_width, self.img_height = img_width, img_height
self.paint_color = paint_color
self.x, self.y = 0, 0
self.age = 0
self.fern = Image.new('RGB', (img_width, img_height), bg_color)
self.pix = self.fern.load()
self.pix[self.scale(0, 0)] = paint_color
def scale(self, x, y):
h = (x + 2.182)*(self.img_width - 1)/4.8378
k = (9.9983 - y)*(self.img_height - 1)/9.9983
return h, k
def transform(self, x, y):
rand = random.uniform(0, 100)
if rand < 1:
return 0, 0.16*y
elif 1 <= rand < 86:
return 0.85*x + 0.04*y, -0.04*x + 0.85*y + 1.6
elif 86 <= rand < 93:
return 0.2*x - 0.26*y, 0.23*x + 0.22*y + 1.6
else:
return -0.15*x + 0.28*y, 0.26*x + 0.24*y + 0.44
def iterate(self, iterations):
for _ in range(iterations):
self.x, self.y = self.transform(self.x, self.y)
self.pix[self.scale(self.x, self.y)] = self.paint_color
self.age += iterations
fern = BarnsleyFern(500, 500)
fern.iterate(1000000)
fern.fern.show()
|
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
| #Ring | Ring |
nums = [1,2,3,4,5,6,7,8,9,10]
sum = 0
decimals(5)
see "Average = " + average(nums) + nl
func average number
for i = 1 to len(number)
sum = sum + pow(number[i],2)
next
x = sqrt(sum / len(number))
return x
|
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
| #Ruby | Ruby | class Array
def quadratic_mean
Math.sqrt( self.inject(0.0) {|s, y| s + y*y} / self.length )
end
end
class Range
def quadratic_mean
self.to_a.quadratic_mean
end
end
(1..10).quadratic_mean # => 6.2048368229954285 |
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.
| #Common_Lisp | Common Lisp |
(defun babbage-test (n)
"A generic function for any ending of a number"
(when (> n 0)
(do* ((i 0 (1+ i))
(d (expt 10 (1+ (truncate (log n) (log 10))))) )
((= (mod (* i i) d) n) i) )))
|
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
| #Forth | Forth | : f+! ( f addr -- ) dup f@ f+ f! ;
: ,f0s ( n -- ) falign 0 do 0e f, loop ;
: period @ ;
: used cell+ ;
: head 2 cells + ;
: sum 3 cells + faligned ;
: ring ( addr -- faddr )
dup sum float+ swap head @ floats + ;
: update ( fvalue addr -- addr )
dup ring f@ fnegate dup sum f+!
fdup dup ring f! dup sum f+!
dup head @ 1+ over period mod over head ! ;
: moving-average
create ( period -- ) dup , 0 , 0 , 1+ ,f0s
does> ( fvalue -- avg )
update
dup used @ over period < if 1 over used +! then
dup sum f@ used @ 0 d>f f/ ;
3 moving-average sma
1e sma f. \ 1.
2e sma f. \ 1.5
3e sma f. \ 2.
4e sma f. \ 3. |
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
| #QB64 | QB64 | _Title "Barnsley Fern"
Dim As Integer sw, sh
sw = 400: sh = 600
Screen _NewImage(sw, sh, 8)
Dim As Long i, ox, oy
Dim As Single sRand
Dim As Double x, y, x1, y1, sx, sy
sx = 60: sy = 59
ox = 180: oy = 4
Randomize Timer
x = 0
y = 0
For i = 1 To 400000
sRand = Rnd
Select Case sRand
Case Is < 0.01
x1 = 0: y1 = 0.16 * y
Case Is < 0.08
x1 = 0.2 * x - 0.26 * y: y1 = 0.23 * x + 0.22 * y + 1.6
Case Is < 0.15
x1 = -0.15 * x + 0.28 * y: y1 = 0.26 * x + 0.24 * y + 0.44
Case Else
x1 = 0.85 * x + 0.04 * y: y1 = -0.04 * x + 0.85 * y + 1.6
End Select
x = x1
y = y1
PSet (x * sx + ox, sh - (y * sy) - oy), 10
Next
Sleep
System |
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
| #R | R | ## pBarnsleyFern(fn, n, clr, ttl, psz=600): Plot Barnsley fern fractal.
## Where: fn - file name; n - number of dots; clr - color; ttl - plot title;
## psz - picture size.
## 7/27/16 aev
pBarnsleyFern <- function(fn, n, clr, ttl, psz=600) {
cat(" *** START:", date(), "n=", n, "clr=", clr, "psz=", psz, "\n");
cat(" *** File name -", fn, "\n");
pf = paste0(fn,".png"); # pf - plot file name
A1 <- matrix(c(0,0,0,0.16,0.85,-0.04,0.04,0.85,0.2,0.23,-0.26,0.22,-0.15,0.26,0.28,0.24), ncol=4, nrow=4, byrow=TRUE);
A2 <- matrix(c(0,0,0,1.6,0,1.6,0,0.44), ncol=2, nrow=4, byrow=TRUE);
P <- c(.01,.85,.07,.07);
# Creating matrices M1 and M2.
M1=vector("list", 4); M2 = vector("list", 4);
for (i in 1:4) {
M1[[i]] <- matrix(c(A1[i,1:4]), nrow=2);
M2[[i]] <- matrix(c(A2[i, 1:2]), nrow=2);
}
x <- numeric(n); y <- numeric(n);
x[1] <- y[1] <- 0;
for (i in 1:(n-1)) {
k <- sample(1:4, prob=P, size=1);
M <- as.matrix(M1[[k]]);
z <- M%*%c(x[i],y[i]) + M2[[k]];
x[i+1] <- z[1]; y[i+1] <- z[2];
}
plot(x, y, main=ttl, axes=FALSE, xlab="", ylab="", col=clr, cex=0.1);
# Writing png-file
dev.copy(png, filename=pf,width=psz,height=psz);
# Cleaning
dev.off(); graphics.off();
cat(" *** END:",date(),"\n");
}
## Executing:
pBarnsleyFern("BarnsleyFernR", 100000, "dark green", "Barnsley Fern Fractal", psz=600)
|
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
| #Run_BASIC | Run BASIC | valueList$ = "1 2 3 4 5 6 7 8 9 10"
while word$(valueList$,i +1) <> "" ' grab values from list
thisValue = val(word$(valueList$,i +1)) ' turn values into numbers
sumSquares = sumSquares + thisValue ^ 2 ' sum up the squares
i = i +1 '
wend
print "List of Values:";valueList$;" containing ";i;" values"
print "Root Mean Square =";(sumSquares/i)^0.5 |
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
| #Rust | Rust | fn root_mean_square(vec: Vec<i32>) -> f32 {
let sum_squares = vec.iter().fold(0, |acc, &x| acc + x.pow(2));
return ((sum_squares as f32)/(vec.len() as f32)).sqrt();
}
fn main() {
let vec = (1..11).collect();
println!("The root mean square is: {}", root_mean_square(vec));
} |
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.
| #Component_Pascal | Component Pascal |
MODULE BabbageProblem;
IMPORT StdLog;
PROCEDURE Do*;
VAR
i: LONGINT;
BEGIN
i := 2;
WHILE (i * i MOD 1000000) # 269696 DO
IF i MOD 10 = 4 THEN INC(i,2) ELSE INC(i,8) END
END;
StdLog.Int(i)
END Do;
END BabbageProblem.
|
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
| #Fortran | Fortran | program Movavg
implicit none
integer :: i
write (*, "(a)") "SIMPLE MOVING AVERAGE: PERIOD = 3"
do i = 1, 5
write (*, "(a, i2, a, f8.6)") "Next number:", i, " sma = ", sma(real(i))
end do
do i = 5, 1, -1
write (*, "(a, i2, a, f8.6)") "Next number:", i, " sma = ", sma(real(i))
end do
contains
function sma(n)
real :: sma
real, intent(in) :: n
real, save :: a(3) = 0
integer, save :: count = 0
if (count < 3) then
count = count + 1
a(count) = n
else
a = eoshift(a, 1, n)
end if
sma = sum(a(1:count)) / real(count)
end function
end program Movavg |
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
| #Racket | Racket | #lang racket
(require racket/draw)
(define fern-green (make-color #x32 #xCD #x32 0.66))
(define (fern dc n-iterations w h)
(for/fold ((x #i0) (y #i0))
((i n-iterations))
(define-values (x′ y′)
(let ((r (random)))
(cond
[(<= r 0.01) (values 0
(* y 16/100))]
[(<= r 0.08) (values (+ (* x 20/100) (* y -26/100))
(+ (* x 23/100) (* y 22/100) 16/10))]
[(<= r 0.15) (values (+ (* x -15/100) (* y 28/100))
(+ (* x 26/100) (* y 24/100) 44/100))]
[else (values (+ (* x 85/100) (* y 4/100))
(+ (* x -4/100) (* y 85/100) 16/10))])))
(define px (+ (/ w 2) (* x w 1/11)))
(define py (- h (* y h 1/11)))
(send dc set-pixel (exact-round px) (exact-round py) fern-green)
(values x′ y′)))
(define bmp (make-object bitmap% 640 640 #f #t 2))
(fern (new bitmap-dc% [bitmap bmp]) 200000 640 640)
bmp
(send bmp save-file "images/racket-barnsley-fern.png" 'png) |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.