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/Arithmetic-geometric_mean/Calculate_Pi | Arithmetic-geometric mean/Calculate Pi | Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate
π
{\displaystyle \pi }
.
With the same notations used in Arithmetic-geometric mean, we can summarize the paper by writing:
π
=
4
a
g
m
(
1
,
1
/
2
)
2
1
−
∑
n
=
1
∞
2
n
+
1
(
a
n
2
−
g
n
2
)
{\displaystyle \pi ={\frac {4\;\mathrm {agm} (1,1/{\sqrt {2}})^{2}}{1-\sum \limits _{n=1}^{\infty }2^{n+1}(a_{n}^{2}-g_{n}^{2})}}}
This allows you to make the approximation, for any large N:
π
≈
4
a
N
2
1
−
∑
k
=
1
N
2
k
+
1
(
a
k
2
−
g
k
2
)
{\displaystyle \pi \approx {\frac {4\;a_{N}^{2}}{1-\sum \limits _{k=1}^{N}2^{k+1}(a_{k}^{2}-g_{k}^{2})}}}
The purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of
π
{\displaystyle \pi }
.
| #Kotlin | Kotlin | import java.math.BigDecimal
import java.math.MathContext
val con1024 = MathContext(1024)
val bigTwo = BigDecimal(2)
val bigFour = bigTwo * bigTwo
fun bigSqrt(bd: BigDecimal, con: MathContext): BigDecimal {
var x0 = BigDecimal.ZERO
var x1 = BigDecimal.valueOf(Math.sqrt(bd.toDouble()))
while (x0 != x1) {
x0 = x1
x1 = bd.divide(x0, con).add(x0).divide(bigTwo, con)
}
return x1
}
fun main(args: Array<String>) {
var a = BigDecimal.ONE
var g = a.divide(bigSqrt(bigTwo, con1024), con1024)
var t : BigDecimal
var sum = BigDecimal.ZERO
var pow = bigTwo
while (a != g) {
t = (a + g).divide(bigTwo, con1024)
g = bigSqrt(a * g, con1024)
a = t
pow *= bigTwo
sum += (a * a - g * g) * pow
}
val pi = (bigFour * a * a).divide(BigDecimal.ONE - sum, con1024)
println(pi)
} |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #Arendelle | Arendelle | // Creating an array as [ 23, 12, 2, 5345, 23 ]
// with name "space"
( space , 23; 12; 2; 5345; 23 )
// Getting the size of an array:
"Size of array is | @space? |"
// Appending array with 54
( space[ @space? ] , 54 )
// Something else fun about arrays in Arendelle
// for example when you have one like this:
//
// space -> [ 23, 34, 3, 6345 ]
//
// If you do this on the space:
( space[ 7 ] , 10 )
// Arendelle will make the size of array into
// 8 by appending zeros and then it will set
// index 7 to 10 and result will be:
//
// space -> [ 23, 34, 3, 6345, 0, 0, 0, 10 ]
// To remove the array you can use done keyword:
( space , done ) |
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part", where the imaginary part is the number to be multiplied by
i
{\displaystyle i}
.
Task
Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.)
Print the results for each operation tested.
Optional: Show complex conjugation.
By definition, the complex conjugate of
a
+
b
i
{\displaystyle a+bi}
is
a
−
b
i
{\displaystyle a-bi}
Some languages have complex number libraries available. If your language does, show the operations. If your language does not, also show the definition of this type.
| #BBC_BASIC | BBC BASIC | DIM Complex{r, i}
DIM a{} = Complex{} : a.r = 1.0 : a.i = 1.0
DIM b{} = Complex{} : b.r = PI# : b.i = 1.2
DIM o{} = Complex{}
PROCcomplexadd(o{}, a{}, b{})
PRINT "Result of addition is " FNcomplexshow(o{})
PROCcomplexmul(o{}, a{}, b{})
PRINT "Result of multiplication is " ; FNcomplexshow(o{})
PROCcomplexneg(o{}, a{})
PRINT "Result of negation is " ; FNcomplexshow(o{})
PROCcomplexinv(o{}, a{})
PRINT "Result of inversion is " ; FNcomplexshow(o{})
END
DEF PROCcomplexadd(dst{}, one{}, two{})
dst.r = one.r + two.r
dst.i = one.i + two.i
ENDPROC
DEF PROCcomplexmul(dst{}, one{}, two{})
dst.r = one.r*two.r - one.i*two.i
dst.i = one.i*two.r + one.r*two.i
ENDPROC
DEF PROCcomplexneg(dst{}, src{})
dst.r = -src.r
dst.i = -src.i
ENDPROC
DEF PROCcomplexinv(dst{}, src{})
LOCAL denom : denom = src.r^2 + src.i^ 2
dst.r = src.r / denom
dst.i = -src.i / denom
ENDPROC
DEF FNcomplexshow(src{})
IF src.i >= 0 THEN = STR$(src.r) + " + " +STR$(src.i) + "i"
= STR$(src.r) + " - " + STR$(-src.i) + "i" |
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part", where the imaginary part is the number to be multiplied by
i
{\displaystyle i}
.
Task
Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.)
Print the results for each operation tested.
Optional: Show complex conjugation.
By definition, the complex conjugate of
a
+
b
i
{\displaystyle a+bi}
is
a
−
b
i
{\displaystyle a-bi}
Some languages have complex number libraries available. If your language does, show the operations. If your language does not, also show the definition of this type.
| #Bracmat | Bracmat | (add=a b.!arg:(?a,?b)&!a+!b)
& ( multiply
= a b.!arg:(?a,?b)&1+!a*!b+-1
)
& (negate=.1+-1*!arg+-1)
& ( conjugate
= a b
. !arg:i&-i
| !arg:-i&i
| !arg:?a_?b&(conjugate$!a)_(conjugate$!b)
| !arg
)
& ( invert
= conjugated
. conjugate$!arg:?conjugated
& multiply$(!arg,!conjugated)^-1*!conjugated
)
& out$("(a+i*b)+(a+i*b) =" add$(a+i*b,a+i*b))
& out$("(a+i*b)+(a+-i*b) =" add$(a+i*b,a+-i*b))
& out$("(a+i*b)*(a+i*b) =" multiply$(a+i*b,a+i*b))
& out$("(a+i*b)*(a+-i*b) =" multiply$(a+i*b,a+-i*b))
& out$("-1*(a+i*b) =" negate$(a+i*b))
& out$("-1*(a+-i*b) =" negate$(a+-i*b))
& out$("sin$x = " sin$x)
& out$("conjugate sin$x =" conjugate$(sin$x))
& out
$ ("sin$x minus conjugate sin$x =" sin$x+negate$(conjugate$(sin$x)))
& done; |
http://rosettacode.org/wiki/Arena_storage_pool | Arena storage pool | Dynamically allocated objects take their memory from a heap.
The memory for an object is provided by an allocator which maintains the storage pool used for the heap.
Often a call to allocator is denoted as
P := new T
where T is the type of an allocated object, and P is a reference to the object.
The storage pool chosen by the allocator can be determined by either:
the object type T
the type of pointer P
In the former case objects can be allocated only in one storage pool.
In the latter case objects of the type can be allocated in any storage pool or on the stack.
Task
The task is to show how allocators and user-defined storage pools are supported by the language.
In particular:
define an arena storage pool. An arena is a pool in which objects are allocated individually, but freed by groups.
allocate some objects (e.g., integers) in the pool.
Explain what controls the storage pool choice in the language.
| #Fortran | Fortran | SUBROUTINE CHECK(A,N) !Inspect matrix A.
REAL A(:,:) !The matrix, whatever size it is.
INTEGER N !The order.
REAL B(N,N) !A scratchpad, size known on entry..
INTEGER, ALLOCATABLE::TROUBLE(:) !But for this, I'll decide later.
INTEGER M
M = COUNT(A(1:N,1:N).LE.0) !Some maximum number of troublemakers.
ALLOCATE (TROUBLE(1:M**3)) !Just enough.
DEALLOCATE(TROUBLE) !Not necessary.
END SUBROUTINE CHECK !As TROUBLE is declared within CHECK. |
http://rosettacode.org/wiki/Arena_storage_pool | Arena storage pool | Dynamically allocated objects take their memory from a heap.
The memory for an object is provided by an allocator which maintains the storage pool used for the heap.
Often a call to allocator is denoted as
P := new T
where T is the type of an allocated object, and P is a reference to the object.
The storage pool chosen by the allocator can be determined by either:
the object type T
the type of pointer P
In the former case objects can be allocated only in one storage pool.
In the latter case objects of the type can be allocated in any storage pool or on the stack.
Task
The task is to show how allocators and user-defined storage pools are supported by the language.
In particular:
define an arena storage pool. An arena is a pool in which objects are allocated individually, but freed by groups.
allocate some objects (e.g., integers) in the pool.
Explain what controls the storage pool choice in the language.
| #FreeBASIC | FreeBASIC |
/' FreeBASIC admite tres tipos básicos de asignación de memoria:
- La asignación estática se produce para variables estáticas y globales.
La memoria se asigna una vez cuando el programa se ejecuta y persiste durante
toda la vida del programa.
- La asignación de pila se produce para parámetros de procedimiento y variables
locales. La memoria se asigna cuando se ingresa el bloque correspondiente y se
libera cuando se deja el bloque, tantas veces como sea necesario.
- La asignación dinámica es el tema de este artículo.
La asignación estática y la asignación de pila tienen dos cosas en común:
- El tamaño de la variable debe conocerse en el momento de la compilación.
- La asignación y desasignación de memoria ocurren automáticamente (cuando se
crea una instancia de la variable y luego se destruye). El usuario no puede
anticipar la destrucción de dicha variable.
La mayoría de las veces, eso está bien. Sin embargo, hay situaciones en las que
una u otra de estas restricciones causan problemas (cuando la memoria necesaria
depende de la entrada del usuario, el tamaño solo se puede determinar durante el
tiempo de ejecución).
1) Palabras clave para la asignación de memoria dinámica:
Hay dos conjuntos de palabras clave para la asignación / desasignación dinámica:
* Allocate / Callocate / Reallocate / Deallocate: para la asignación de
memoria bruta y luego la desasignación, para tipos simples predefinidos
o búferes de usuario.
* New / Delete: para asignación de memoria + construcción, luego
destrucción + desasignación.
Se desaconseja encarecidamente mezclar palabras clave entre estos dos
conjuntos cuando se gestiona un mismo bloque de memoria.
2) Variante usando Redim / Erase:
FreeBASIC también admite matrices dinámicas (matrices de longitud variable).
La memoria utilizada por una matriz dinámica para almacenar sus elementos se
asigna en tiempo de ejecución en el montón. Las matrices dinámicas pueden
contener tipos simples y objetos complejos.
Al usar Redim, el usuario no necesita llamar al Constructor / Destructor
porque Redim lo hace automáticamente cuando agrega / elimina un elemento.
Erase luego destruye todos los elementos restantes para liberar completamente
la memoria asignada a ellos.
'/
Type UDT
Dim As String S = "FreeBASIC" '' induce an implicit constructor and destructor
End Type
' 3 then 4 objects: Callocate, Reallocate, Deallocate, (+ .constructor + .destructor)
Dim As UDT Ptr p1 = Callocate(3, Sizeof(UDT)) '' allocate cleared memory for 3 elements (string descriptors cleared,
'' but maybe useless because of the constructor's call right behind)
For I As Integer = 0 To 2
p1[I].Constructor() '' call the constructor on each element
Next I
For I As Integer = 0 To 2
p1[I].S &= Str(I) '' add the element number to the string of each element
Next I
For I As Integer = 0 To 2
Print "'" & p1[I].S & "'", '' print each element string
Next I
Print
p1 = Reallocate(p1, 4 * Sizeof(UDT)) '' reallocate memory for one additional element
Clear p1[3], 0, 3 * Sizeof(Integer) '' clear the descriptor of the additional element,
'' but maybe useless because of the constructor's call right behind
p1[3].Constructor() '' call the constructor on the additional element
p1[3].S &= Str(3) '' add the element number to the string of the additional element
For I As Integer = 0 To 3
Print "'" & p1[I].S & "'", '' print each element string
Next I
Print
For I As Integer = 0 To 3
p1[I].Destructor() '' call the destructor on each element
Next I
Deallocate(p1) '' deallocate the memory
Print
' 3 objects: New, Delete
Dim As UDT Ptr p2 = New UDT[3] '' allocate memory and construct 3 elements
For I As Integer = 0 To 2
p2[I].S &= Str(I) '' add the element number to the string of each element
Next I
For I As Integer = 0 To 2
Print "'" & p2[I].S & "'", '' print each element string
Next I
Print
Delete [] p2 '' destroy the 3 element and deallocate the memory
Print
' 3 objects: Placement New, (+ .destructor)
Redim As Byte array(0 To 3 * Sizeof(UDT) - 1) '' allocate buffer for 3 elements
Dim As Any Ptr p = @array(0)
Dim As UDT Ptr p3 = New(p) UDT[3] '' only construct the 3 elements in the buffer (placement New)
For I As Integer = 0 To 2
p3[I].S &= Str(I) '' add the element number to the string of each element
Next I
For I As Integer = 0 To 2
Print "'" & p3[I].S & "'", '' print each element string
Next I
Print
For I As Integer = 0 To 2
p3[I].Destructor() '' call the destructor on each element
Next I
Erase array '' deallocate the buffer
Print
' 3 then 4 objects: Redim, Erase
Redim As UDT p4(0 To 2) '' define a dynamic array of 3 elements
For I As Integer = 0 To 2
p4(I).S &= Str(I) '' add the element number to the string of each element
Next I
For I As Integer = 0 To 2
Print "'" & p4(I).S & "'", '' print each element string
Next I
Print
Redim Preserve p4(0 To 3) '' resize the dynamic array for one additional element
p4(3).S &= Str(3) '' add the element number to the string of the additional element
For I As Integer = 0 To 3
Print "'" & p4(I).S & "'", '' print each element string
Next I
Print
Erase p4 '' erase the dynamic array
Print
Sleep
|
http://rosettacode.org/wiki/Arithmetic/Rational | Arithmetic/Rational | Task
Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language.
Example
Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number).
Further define the appropriate rational unary operators abs and '-', with the binary operators for addition '+', subtraction '-', multiplication '×', division '/', integer division '÷', modulo division, the comparison operators (e.g. '<', '≤', '>', & '≥') and equality operators (e.g. '=' & '≠').
Define standard coercion operators for casting int to frac etc.
If space allows, define standard increment and decrement operators (e.g. '+:=' & '-:=' etc.).
Finally test the operators:
Use the new type frac to find all perfect numbers less than 219 by summing the reciprocal of the factors.
Related task
Perfect Numbers
| #C | C | #include <stdio.h>
#include <stdlib.h>
#define FMT "%lld"
typedef long long int fr_int_t;
typedef struct { fr_int_t num, den; } frac;
fr_int_t gcd(fr_int_t m, fr_int_t n)
{
fr_int_t t;
while (n) { t = n; n = m % n; m = t; }
return m;
}
frac frac_new(fr_int_t num, fr_int_t den)
{
frac a;
if (!den) {
printf("divide by zero: "FMT"/"FMT"\n", num, den);
abort();
}
int g = gcd(num, den);
if (g) { num /= g; den /= g; }
else { num = 0; den = 1; }
if (den < 0) {
den = -den;
num = -num;
}
a.num = num; a.den = den;
return a;
}
#define BINOP(op, n, d) frac frac_##op(frac a, frac b) { return frac_new(n,d); }
BINOP(add, a.num * b.den + b.num * a.den, a.den * b.den);
BINOP(sub, a.num * b.den - b.num + a.den, a.den * b.den);
BINOP(mul, a.num * b.num, a.den * b.den);
BINOP(div, a.num * b.den, a.den * b.num);
int frac_cmp(frac a, frac b) {
int l = a.num * b.den, r = a.den * b.num;
return l < r ? -1 : l > r;
}
#define frac_cmp_int(a, b) frac_cmp(a, frac_new(b, 1))
int frtoi(frac a) { return a.den / a.num; }
double frtod(frac a) { return (double)a.den / a.num; }
int main()
{
int n, k;
frac sum, kf;
for (n = 2; n < 1<<19; n++) {
sum = frac_new(1, n);
for (k = 2; k * k < n; k++) {
if (n % k) continue;
kf = frac_new(1, k);
sum = frac_add(sum, kf);
kf = frac_new(1, n / k);
sum = frac_add(sum, kf);
}
if (frac_cmp_int(sum, 1) == 0) printf("%d\n", n);
}
return 0;
} |
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geometric mean of two numbers.
The arithmetic-geometric mean of two numbers can be (usefully) denoted as
a
g
m
(
a
,
g
)
{\displaystyle \mathrm {agm} (a,g)}
, and is equal to the limit of the sequence:
a
0
=
a
;
g
0
=
g
{\displaystyle a_{0}=a;\qquad g_{0}=g}
a
n
+
1
=
1
2
(
a
n
+
g
n
)
;
g
n
+
1
=
a
n
g
n
.
{\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.}
Since the limit of
a
n
−
g
n
{\displaystyle a_{n}-g_{n}}
tends (rapidly) to zero with iterations, this is an efficient method.
Demonstrate the function by calculating:
a
g
m
(
1
,
1
/
2
)
{\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})}
Also see
mathworld.wolfram.com/Arithmetic-Geometric Mean
| #AutoHotkey | AutoHotkey | agm(a, g, tolerance=1.0e-15){
While abs(a-g) > tolerance
{
an := .5 * (a + g)
g := sqrt(a*g)
a := an
}
return a
}
SetFormat, FloatFast, 0.15
MsgBox % agm(1, 1/sqrt(2)) |
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geometric mean of two numbers.
The arithmetic-geometric mean of two numbers can be (usefully) denoted as
a
g
m
(
a
,
g
)
{\displaystyle \mathrm {agm} (a,g)}
, and is equal to the limit of the sequence:
a
0
=
a
;
g
0
=
g
{\displaystyle a_{0}=a;\qquad g_{0}=g}
a
n
+
1
=
1
2
(
a
n
+
g
n
)
;
g
n
+
1
=
a
n
g
n
.
{\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.}
Since the limit of
a
n
−
g
n
{\displaystyle a_{n}-g_{n}}
tends (rapidly) to zero with iterations, this is an efficient method.
Demonstrate the function by calculating:
a
g
m
(
1
,
1
/
2
)
{\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})}
Also see
mathworld.wolfram.com/Arithmetic-Geometric Mean
| #AWK | AWK | #!/usr/bin/awk -f
BEGIN {
printf "%.16g\n", agm(1.0,sqrt(0.5))
}
function agm(a,g) {
while (1) {
a0=a
a=(a0+g)/2
g=sqrt(a0*g)
if (abs(a0-a) < abs(a)*1e-15) break
}
return a
}
function abs(x) {
return (x<0 ? -x : x)
}
|
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Get two integers from the user, and then (for those two integers), display their:
sum
difference
product
integer quotient
remainder
exponentiation (if the operator exists)
Don't include error handling.
For quotient, indicate how it rounds (e.g. towards zero, towards negative infinity, etc.).
For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
| #SSEM | SSEM | 00101000000000100000000000000000 0. -20 to c
10100000000001100000000000000000 1. c to 5
10100000000000100000000000000000 2. -5 to c
10101000000000010000000000000000 3. Sub. 21
00000000000001110000000000000000 4. Stop
00000000000000000000000000000000 5. 0 |
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Get two integers from the user, and then (for those two integers), display their:
sum
difference
product
integer quotient
remainder
exponentiation (if the operator exists)
Don't include error handling.
For quotient, indicate how it rounds (e.g. towards zero, towards negative infinity, etc.).
For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
| #Standard_ML | Standard ML | val () = let
val a = valOf (Int.fromString (valOf (TextIO.inputLine TextIO.stdIn)))
val b = valOf (Int.fromString (valOf (TextIO.inputLine TextIO.stdIn)))
in
print ("a + b = " ^ Int.toString (a + b) ^ "\n");
print ("a - b = " ^ Int.toString (a - b) ^ "\n");
print ("a * b = " ^ Int.toString (a * b) ^ "\n");
print ("a div b = " ^ Int.toString (a div b) ^ "\n"); (* truncates towards negative infinity *)
print ("a mod b = " ^ Int.toString (a mod b) ^ "\n"); (* same sign as second operand *)
print ("a quot b = " ^ Int.toString (Int.quot (a, b)) ^ "\n");(* truncates towards 0 *)
print ("a rem b = " ^ Int.toString (Int.rem (a, b)) ^ "\n"); (* same sign as first operand *)
print ("~a = " ^ Int.toString (~a) ^ "\n") (* unary negation, unusual notation compared to other languages *)
end |
http://rosettacode.org/wiki/Arithmetic-geometric_mean/Calculate_Pi | Arithmetic-geometric mean/Calculate Pi | Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate
π
{\displaystyle \pi }
.
With the same notations used in Arithmetic-geometric mean, we can summarize the paper by writing:
π
=
4
a
g
m
(
1
,
1
/
2
)
2
1
−
∑
n
=
1
∞
2
n
+
1
(
a
n
2
−
g
n
2
)
{\displaystyle \pi ={\frac {4\;\mathrm {agm} (1,1/{\sqrt {2}})^{2}}{1-\sum \limits _{n=1}^{\infty }2^{n+1}(a_{n}^{2}-g_{n}^{2})}}}
This allows you to make the approximation, for any large N:
π
≈
4
a
N
2
1
−
∑
k
=
1
N
2
k
+
1
(
a
k
2
−
g
k
2
)
{\displaystyle \pi \approx {\frac {4\;a_{N}^{2}}{1-\sum \limits _{k=1}^{N}2^{k+1}(a_{k}^{2}-g_{k}^{2})}}}
The purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of
π
{\displaystyle \pi }
.
| #Maple | Maple | agm:=proc(n)
local a:=1,g:=evalf(sqrt(1/2)),s:=0,p:=4,i;
for i to n do
a,g:=(a+g)/2,sqrt(a*g);
s+=p*(a*a-g*g);
p+=p
od;
4*a*a/(1-s)
end:
Digits:=100000:
d:=agm(16)-evalf(Pi):
evalf[10](d);
# 4.280696926e-89415 |
http://rosettacode.org/wiki/Arithmetic-geometric_mean/Calculate_Pi | Arithmetic-geometric mean/Calculate Pi | Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate
π
{\displaystyle \pi }
.
With the same notations used in Arithmetic-geometric mean, we can summarize the paper by writing:
π
=
4
a
g
m
(
1
,
1
/
2
)
2
1
−
∑
n
=
1
∞
2
n
+
1
(
a
n
2
−
g
n
2
)
{\displaystyle \pi ={\frac {4\;\mathrm {agm} (1,1/{\sqrt {2}})^{2}}{1-\sum \limits _{n=1}^{\infty }2^{n+1}(a_{n}^{2}-g_{n}^{2})}}}
This allows you to make the approximation, for any large N:
π
≈
4
a
N
2
1
−
∑
k
=
1
N
2
k
+
1
(
a
k
2
−
g
k
2
)
{\displaystyle \pi \approx {\frac {4\;a_{N}^{2}}{1-\sum \limits _{k=1}^{N}2^{k+1}(a_{k}^{2}-g_{k}^{2})}}}
The purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of
π
{\displaystyle \pi }
.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | pi[n_, prec_] :=
Module[{a = 1, g = N[1/Sqrt[2], prec], k, s = 0, p = 4},
For[k = 1, k < n, k++,
{a, g} = {N[(a + g)/2, prec], N[Sqrt[a g], prec]};
s += p (a^2 - g^2); p += p]; N[4 a^2/(1 - s), prec]]
pi[7, 100] - N[Pi, 100]
1.2026886537*10^-86
pi[7, 100]
3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628046852228654 |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #Argile | Argile | use std, array
(:::::::::::::::::
: Static arrays :
:::::::::::::::::)
let the array of 2 text aabbArray be Cdata{"aa";"bb"}
let raw array of real :my array: = Cdata {1.0 ; 2.0 ; 3.0} (: auto sized :)
let another_array be an array of 256 byte (: not initialised :)
let (raw array of (array of 3 real)) foobar = Cdata {
{1.0; 2.0; 0.0}
{5.0; 1.0; 3.0}
}
(: macro to get size of static arrays :)
=: <array>.length := -> nat {size of array / (size of array[0])}
printf "%lu, %lu\n" foobar.length (another_array.length) (: 2, 256 :)
(: access :)
another_array[255] = '&'
printf "`%c'\n" another_array[255]
(::::::::::::::::::
: Dynamic arrays :
::::::::::::::::::)
let DynArray = new array of 5 int
DynArray[0] = -42
DynArray = (realloc DynArray (6 * size of DynArray[0])) as (type of DynArray)
DynArray[5] = 243
prints DynArray[0] DynArray[5]
del DynArray |
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part", where the imaginary part is the number to be multiplied by
i
{\displaystyle i}
.
Task
Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.)
Print the results for each operation tested.
Optional: Show complex conjugation.
By definition, the complex conjugate of
a
+
b
i
{\displaystyle a+bi}
is
a
−
b
i
{\displaystyle a-bi}
Some languages have complex number libraries available. If your language does, show the operations. If your language does not, also show the definition of this type.
| #C | C | #include <complex.h>
#include <stdio.h>
void cprint(double complex c)
{
printf("%f%+fI", creal(c), cimag(c));
}
void complex_operations() {
double complex a = 1.0 + 1.0I;
double complex b = 3.14159 + 1.2I;
double complex c;
printf("\na="); cprint(a);
printf("\nb="); cprint(b);
// addition
c = a + b;
printf("\na+b="); cprint(c);
// multiplication
c = a * b;
printf("\na*b="); cprint(c);
// inversion
c = 1.0 / a;
printf("\n1/c="); cprint(c);
// negation
c = -a;
printf("\n-a="); cprint(c);
// conjugate
c = conj(a);
printf("\nconj a="); cprint(c); printf("\n");
} |
http://rosettacode.org/wiki/Arena_storage_pool | Arena storage pool | Dynamically allocated objects take their memory from a heap.
The memory for an object is provided by an allocator which maintains the storage pool used for the heap.
Often a call to allocator is denoted as
P := new T
where T is the type of an allocated object, and P is a reference to the object.
The storage pool chosen by the allocator can be determined by either:
the object type T
the type of pointer P
In the former case objects can be allocated only in one storage pool.
In the latter case objects of the type can be allocated in any storage pool or on the stack.
Task
The task is to show how allocators and user-defined storage pools are supported by the language.
In particular:
define an arena storage pool. An arena is a pool in which objects are allocated individually, but freed by groups.
allocate some objects (e.g., integers) in the pool.
Explain what controls the storage pool choice in the language.
| #Go | Go | package main
import (
"fmt"
"runtime"
"sync"
)
// New to Go 1.3 are sync.Pools, basically goroutine-safe free lists.
// There is overhead in the goroutine-safety and if you do not need this
// you might do better by implementing your own free list.
func main() {
// Task 1: Define a pool (of ints). Just as the task says, a sync.Pool
// allocates individually and can free as a group.
p := sync.Pool{New: func() interface{} {
fmt.Println("pool empty")
return new(int)
}}
// Task 2: Allocate some ints.
i := new(int)
j := new(int)
// Show that they're usable.
*i = 1
*j = 2
fmt.Println(*i + *j) // prints 3
// Task 2 continued: Put allocated ints in pool p.
// Task explanation: Variable p has a pool as its value. Another pool
// could be be created and assigned to a different variable. You choose
// a pool simply by using the appropriate variable, p here.
p.Put(i)
p.Put(j)
// Drop references to i and j. This allows them to be garbage collected;
// that is, freed as a group.
i = nil
j = nil
// Get ints for i and j again, this time from the pool. P.Get may reuse
// an object allocated above as long as objects haven't been garbage
// collected yet; otherwise p.Get will allocate a new object.
i = p.Get().(*int)
j = p.Get().(*int)
*i = 4
*j = 5
fmt.Println(*i + *j) // prints 9
// One more test, this time forcing a garbage collection.
p.Put(i)
p.Put(j)
i = nil
j = nil
runtime.GC()
i = p.Get().(*int)
j = p.Get().(*int)
*i = 7
*j = 8
fmt.Println(*i + *j) // prints 15
} |
http://rosettacode.org/wiki/Arena_storage_pool | Arena storage pool | Dynamically allocated objects take their memory from a heap.
The memory for an object is provided by an allocator which maintains the storage pool used for the heap.
Often a call to allocator is denoted as
P := new T
where T is the type of an allocated object, and P is a reference to the object.
The storage pool chosen by the allocator can be determined by either:
the object type T
the type of pointer P
In the former case objects can be allocated only in one storage pool.
In the latter case objects of the type can be allocated in any storage pool or on the stack.
Task
The task is to show how allocators and user-defined storage pools are supported by the language.
In particular:
define an arena storage pool. An arena is a pool in which objects are allocated individually, but freed by groups.
allocate some objects (e.g., integers) in the pool.
Explain what controls the storage pool choice in the language.
| #J | J | coclass 'integerPool'
require 'jmf'
create=: monad define
Lim=: y*SZI_jmf_
Next=: -SZI_jmf_
Pool=: mema Lim
)
destroy=: monad define
memf Pool
codestroy''
)
alloc=: monad define
assert.Lim >: Next=: Next+SZI_jmf_
r=.Pool,Next,1,JINT
r set y
r
)
get=: adverb define
memr m
)
set=: adverb define
y memw m
) |
http://rosettacode.org/wiki/Arithmetic/Rational | Arithmetic/Rational | Task
Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language.
Example
Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number).
Further define the appropriate rational unary operators abs and '-', with the binary operators for addition '+', subtraction '-', multiplication '×', division '/', integer division '÷', modulo division, the comparison operators (e.g. '<', '≤', '>', & '≥') and equality operators (e.g. '=' & '≠').
Define standard coercion operators for casting int to frac etc.
If space allows, define standard increment and decrement operators (e.g. '+:=' & '-:=' etc.).
Finally test the operators:
Use the new type frac to find all perfect numbers less than 219 by summing the reciprocal of the factors.
Related task
Perfect Numbers
| #C.23 | C# | using System;
struct Fraction : IEquatable<Fraction>, IComparable<Fraction>
{
public readonly long Num;
public readonly long Denom;
public Fraction(long num, long denom)
{
if (num == 0)
{
denom = 1;
}
else if (denom == 0)
{
throw new ArgumentException("Denominator may not be zero", "denom");
}
else if (denom < 0)
{
num = -num;
denom = -denom;
}
long d = GCD(num, denom);
this.Num = num / d;
this.Denom = denom / d;
}
private static long GCD(long x, long y)
{
return y == 0 ? x : GCD(y, x % y);
}
private static long LCM(long x, long y)
{
return x / GCD(x, y) * y;
}
public Fraction Abs()
{
return new Fraction(Math.Abs(Num), Denom);
}
public Fraction Reciprocal()
{
return new Fraction(Denom, Num);
}
#region Conversion Operators
public static implicit operator Fraction(long i)
{
return new Fraction(i, 1);
}
public static explicit operator double(Fraction f)
{
return f.Num == 0 ? 0 : (double)f.Num / f.Denom;
}
#endregion
#region Arithmetic Operators
public static Fraction operator -(Fraction f)
{
return new Fraction(-f.Num, f.Denom);
}
public static Fraction operator +(Fraction a, Fraction b)
{
long m = LCM(a.Denom, b.Denom);
long na = a.Num * m / a.Denom;
long nb = b.Num * m / b.Denom;
return new Fraction(na + nb, m);
}
public static Fraction operator -(Fraction a, Fraction b)
{
return a + (-b);
}
public static Fraction operator *(Fraction a, Fraction b)
{
return new Fraction(a.Num * b.Num, a.Denom * b.Denom);
}
public static Fraction operator /(Fraction a, Fraction b)
{
return a * b.Reciprocal();
}
public static Fraction operator %(Fraction a, Fraction b)
{
long l = a.Num * b.Denom, r = a.Denom * b.Num;
long n = l / r;
return new Fraction(l - n * r, a.Denom * b.Denom);
}
#endregion
#region Comparison Operators
public static bool operator ==(Fraction a, Fraction b)
{
return a.Num == b.Num && a.Denom == b.Denom;
}
public static bool operator !=(Fraction a, Fraction b)
{
return a.Num != b.Num || a.Denom != b.Denom;
}
public static bool operator <(Fraction a, Fraction b)
{
return (a.Num * b.Denom) < (a.Denom * b.Num);
}
public static bool operator >(Fraction a, Fraction b)
{
return (a.Num * b.Denom) > (a.Denom * b.Num);
}
public static bool operator <=(Fraction a, Fraction b)
{
return !(a > b);
}
public static bool operator >=(Fraction a, Fraction b)
{
return !(a < b);
}
#endregion
#region Object Members
public override bool Equals(object obj)
{
if (obj is Fraction)
return ((Fraction)obj) == this;
else
return false;
}
public override int GetHashCode()
{
return Num.GetHashCode() ^ Denom.GetHashCode();
}
public override string ToString()
{
return Num.ToString() + "/" + Denom.ToString();
}
#endregion
#region IEquatable<Fraction> Members
public bool Equals(Fraction other)
{
return other == this;
}
#endregion
#region IComparable<Fraction> Members
public int CompareTo(Fraction other)
{
return (this.Num * other.Denom).CompareTo(this.Denom * other.Num);
}
#endregion
} |
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geometric mean of two numbers.
The arithmetic-geometric mean of two numbers can be (usefully) denoted as
a
g
m
(
a
,
g
)
{\displaystyle \mathrm {agm} (a,g)}
, and is equal to the limit of the sequence:
a
0
=
a
;
g
0
=
g
{\displaystyle a_{0}=a;\qquad g_{0}=g}
a
n
+
1
=
1
2
(
a
n
+
g
n
)
;
g
n
+
1
=
a
n
g
n
.
{\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.}
Since the limit of
a
n
−
g
n
{\displaystyle a_{n}-g_{n}}
tends (rapidly) to zero with iterations, this is an efficient method.
Demonstrate the function by calculating:
a
g
m
(
1
,
1
/
2
)
{\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})}
Also see
mathworld.wolfram.com/Arithmetic-Geometric Mean
| #BASIC | BASIC | PRINT AGM(1, 1 / SQR(2))
END
FUNCTION AGM (a, g)
DO
ta = (a + g) / 2
g = SQR(a * g)
SWAP a, ta
LOOP UNTIL a = ta
AGM = a
END FUNCTION |
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geometric mean of two numbers.
The arithmetic-geometric mean of two numbers can be (usefully) denoted as
a
g
m
(
a
,
g
)
{\displaystyle \mathrm {agm} (a,g)}
, and is equal to the limit of the sequence:
a
0
=
a
;
g
0
=
g
{\displaystyle a_{0}=a;\qquad g_{0}=g}
a
n
+
1
=
1
2
(
a
n
+
g
n
)
;
g
n
+
1
=
a
n
g
n
.
{\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.}
Since the limit of
a
n
−
g
n
{\displaystyle a_{n}-g_{n}}
tends (rapidly) to zero with iterations, this is an efficient method.
Demonstrate the function by calculating:
a
g
m
(
1
,
1
/
2
)
{\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})}
Also see
mathworld.wolfram.com/Arithmetic-Geometric Mean
| #bc | bc | /* Calculate the arithmethic-geometric mean of two positive
* numbers x and y.
* Result will have d digits after the decimal point.
*/
define m(x, y, d) {
auto a, g, o
o = scale
scale = d
d = 1 / 10 ^ d
a = (x + y) / 2
g = sqrt(x * y)
while ((a - g) > d) {
x = (a + g) / 2
g = sqrt(a * g)
a = x
}
scale = o
return(a)
}
scale = 20
m(1, 1 / sqrt(2), 20) |
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Get two integers from the user, and then (for those two integers), display their:
sum
difference
product
integer quotient
remainder
exponentiation (if the operator exists)
Don't include error handling.
For quotient, indicate how it rounds (e.g. towards zero, towards negative infinity, etc.).
For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
| #Swift | Swift |
let a = 6
let b = 4
print("sum =\(a+b)")
print("difference = \(a-b)")
print("product = \(a*b)")
print("Integer quotient = \(a/b)")
print("Remainder = (a%b)")
print("No operator for Exponential")
|
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Get two integers from the user, and then (for those two integers), display their:
sum
difference
product
integer quotient
remainder
exponentiation (if the operator exists)
Don't include error handling.
For quotient, indicate how it rounds (e.g. towards zero, towards negative infinity, etc.).
For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
| #Tcl | Tcl | puts "Please enter two numbers:"
set x [expr {int([gets stdin])}]; # Force integer interpretation
set y [expr {int([gets stdin])}]; # Force integer interpretation
puts "$x + $y = [expr {$x + $y}]"
puts "$x - $y = [expr {$x - $y}]"
puts "$x * $y = [expr {$x * $y}]"
puts "$x / $y = [expr {$x / $y}]"
puts "$x mod $y = [expr {$x % $y}]"
puts "$x 'to the' $y = [expr {$x ** $y}]" |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #11l | 11l | V doors = [0B] * 100
L(i) 100
L(j) (i .< 100).step(i + 1)
doors[j] = !doors[j]
print(‘Door ’(i + 1)‘: ’(I doors[i] {‘open’} E ‘close’)) |
http://rosettacode.org/wiki/Arithmetic-geometric_mean/Calculate_Pi | Arithmetic-geometric mean/Calculate Pi | Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate
π
{\displaystyle \pi }
.
With the same notations used in Arithmetic-geometric mean, we can summarize the paper by writing:
π
=
4
a
g
m
(
1
,
1
/
2
)
2
1
−
∑
n
=
1
∞
2
n
+
1
(
a
n
2
−
g
n
2
)
{\displaystyle \pi ={\frac {4\;\mathrm {agm} (1,1/{\sqrt {2}})^{2}}{1-\sum \limits _{n=1}^{\infty }2^{n+1}(a_{n}^{2}-g_{n}^{2})}}}
This allows you to make the approximation, for any large N:
π
≈
4
a
N
2
1
−
∑
k
=
1
N
2
k
+
1
(
a
k
2
−
g
k
2
)
{\displaystyle \pi \approx {\frac {4\;a_{N}^{2}}{1-\sum \limits _{k=1}^{N}2^{k+1}(a_{k}^{2}-g_{k}^{2})}}}
The purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of
π
{\displaystyle \pi }
.
| #.D0.9C.D0.9A-61.2F52 | МК-61/52 | 3 П0 1 П1 П4 2 КвКор 1/x П2 1
^ 4 / П3 ИП3 ИП1 ИП2 + 2 /
П5 ИП1 - x^2 ИП4 * - П3 ИП1 ИП2
* КвКор П2 ИП5 П1 КИП4 L0 14 ИП1 x^2
ИП3 / С/П |
http://rosettacode.org/wiki/Arithmetic-geometric_mean/Calculate_Pi | Arithmetic-geometric mean/Calculate Pi | Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate
π
{\displaystyle \pi }
.
With the same notations used in Arithmetic-geometric mean, we can summarize the paper by writing:
π
=
4
a
g
m
(
1
,
1
/
2
)
2
1
−
∑
n
=
1
∞
2
n
+
1
(
a
n
2
−
g
n
2
)
{\displaystyle \pi ={\frac {4\;\mathrm {agm} (1,1/{\sqrt {2}})^{2}}{1-\sum \limits _{n=1}^{\infty }2^{n+1}(a_{n}^{2}-g_{n}^{2})}}}
This allows you to make the approximation, for any large N:
π
≈
4
a
N
2
1
−
∑
k
=
1
N
2
k
+
1
(
a
k
2
−
g
k
2
)
{\displaystyle \pi \approx {\frac {4\;a_{N}^{2}}{1-\sum \limits _{k=1}^{N}2^{k+1}(a_{k}^{2}-g_{k}^{2})}}}
The purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of
π
{\displaystyle \pi }
.
| #Nim | Nim | from math import sqrt
import times
import bignum
#---------------------------------------------------------------------------------------------------
func sqrt(value, guess: Int): Int =
result = guess
while true:
let term = value div result
if abs(term - result) <= 1:
break
result = (result + term) shr 1
#---------------------------------------------------------------------------------------------------
func isr(term, guess: Int): Int =
var term = term
result = guess
let value = term * result
while true:
if abs(term - result) <= 1:
break
result = (result + term) shr 1
term = value div result
#---------------------------------------------------------------------------------------------------
func calcAGM(lam, gm: Int; z: var Int; ep: Int): Int =
var am: Int
var lam = lam
var gm = gm
var n = 1
while true:
am = (lam + gm) shr 1
gm = isr(lam, gm)
let v = am - lam
let zi = v * v * n
if zi < ep:
break
dec z, zi
inc n, n
lam = am
result = am
#---------------------------------------------------------------------------------------------------
func bip(exp: int; man = 1): Int {.inline.} = man * pow(10, culong(exp))
#---------------------------------------------------------------------------------------------------
func compress(str: string; size: int): string =
if str.len <= 2 * size: str
else: str[0..<size] & "..." & str[^size..^1]
#———————————————————————————————————————————————————————————————————————————————————————————————————
import os
import parseutils
import strutils
const DefaultDigits = 25_000
var d = DefaultDigits
if paramCount() > 0:
if paramStr(1).parseInt(d) > 0:
if d notin 1..999_999:
d = DefaultDigits
let t0 = getTime()
let am = bip(d)
let gm = sqrt(bip(d + d - 1, 5), bip(d - 15, int(sqrt(0.5) * 1e15)))
var z = bip(d + d - 2, 25)
let agm = calcAGM(am, gm, z, bip(d + 1))
let pi = agm * agm * bip(d - 2) div z
var piStr = $pi
piStr.insert(".", 1)
let dt = (getTime() - t0).inMicroseconds.float
let timestr = if dt > 1_000_000:
(dt / 1e6).formatFloat(ffDecimal, 2) & " s"
elif dt > 1000:
$(dt / 1e3).toInt & " ms"
else:
$dt.toInt & " µs"
echo "Computed ", d, " digits in ", timeStr
echo "π = ", compress(piStr, 20), "..." |
http://rosettacode.org/wiki/Arithmetic-geometric_mean/Calculate_Pi | Arithmetic-geometric mean/Calculate Pi | Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate
π
{\displaystyle \pi }
.
With the same notations used in Arithmetic-geometric mean, we can summarize the paper by writing:
π
=
4
a
g
m
(
1
,
1
/
2
)
2
1
−
∑
n
=
1
∞
2
n
+
1
(
a
n
2
−
g
n
2
)
{\displaystyle \pi ={\frac {4\;\mathrm {agm} (1,1/{\sqrt {2}})^{2}}{1-\sum \limits _{n=1}^{\infty }2^{n+1}(a_{n}^{2}-g_{n}^{2})}}}
This allows you to make the approximation, for any large N:
π
≈
4
a
N
2
1
−
∑
k
=
1
N
2
k
+
1
(
a
k
2
−
g
k
2
)
{\displaystyle \pi \approx {\frac {4\;a_{N}^{2}}{1-\sum \limits _{k=1}^{N}2^{k+1}(a_{k}^{2}-g_{k}^{2})}}}
The purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of
π
{\displaystyle \pi }
.
| #OCaml | OCaml | let limit = 10000 and n = 2800
let x = Array.make (n+1) 2000
let rec g j sum =
if j < 1 then sum else
let sum = sum * j + limit * x.(j) in
x.(j) <- sum mod (j * 2 - 1);
g (j - 1) (sum / (j * 2 - 1))
let rec f i carry =
if i = 0 then () else
let sum = g i 0 in
Printf.printf "%04d" (carry + sum / limit);
f (i - 14) (sum mod limit)
let () =
f n 0;
print_newline()
|
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program areaString.s */
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/* Initialized data */
.data
szMessStringsch: .ascii "The string is at item : "
sZoneconv: .fill 12,1,' '
szCarriageReturn: .asciz "\n"
szMessStringNfound: .asciz "The string is not found in this area.\n"
/* areas strings */
szString1: .asciz "Apples"
szString2: .asciz "Oranges"
szString3: .asciz "Pommes"
szString4: .asciz "Raisins"
szString5: .asciz "Abricots"
/* pointer items area 1*/
tablesPoi1:
pt1_1: .int szString1
pt1_2: .int szString2
pt1_3: .int szString3
pt1_4: .int szString4
ptVoid_1: .int 0
ptVoid_2: .int 0
ptVoid_3: .int 0
ptVoid_4: .int 0
ptVoid_5: .int 0
szStringSch: .asciz "Raisins"
szStringSch1: .asciz "Ananas"
/* UnInitialized data */
.bss
/* code section */
.text
.global main
main: /* entry of program */
push {fp,lr} /* saves 2 registers */
@@@@@@@@@@@@@@@@@@@@@@@@
@ add string 5 to area
@@@@@@@@@@@@@@@@@@@@@@@@
ldr r1,iAdrtablesPoi1 @ begin pointer area 1
mov r0,#0 @ counter
1: @ search first void pointer
ldr r2,[r1,r0,lsl #2] @ read string pointer address item r0 (4 bytes by pointer)
cmp r2,#0 @ is null ?
addne r0,#1 @ no increment counter
bne 1b @ and loop
@ store pointer string 5 in area at position r0
ldr r2,iAdrszString5 @ address string 5
str r2,[r1,r0,lsl #2] @ store address
@@@@@@@@@@@@@@@@@@@@@@@@
@ display string at item 3
@@@@@@@@@@@@@@@@@@@@@@@@
mov r2,#2 @ pointers begin in position 0
ldr r1,iAdrtablesPoi1 @ begin pointer area 1
ldr r0,[r1,r2,lsl #2]
bl affichageMess
ldr r0,iAdrszCarriageReturn
bl affichageMess
@@@@@@@@@@@@@@@@@@@@@@@@
@ search string in area
@@@@@@@@@@@@@@@@@@@@@@@@
ldr r1,iAdrszStringSch
//ldr r1,iAdrszStringSch1 @ uncomment for other search : not found !!
ldr r2,iAdrtablesPoi1 @ begin pointer area 1
mov r3,#0
2: @ search
ldr r0,[r2,r3,lsl #2] @ read string pointer address item r0 (4 bytes by pointer)
cmp r0,#0 @ is null ?
beq 3f @ end search
bl comparaison
cmp r0,#0 @ string = ?
addne r3,#1 @ no increment counter
bne 2b @ and loop
mov r0,r3 @ position item string
ldr r1,iAdrsZoneconv @ conversion decimal
bl conversion10S
ldr r0,iAdrszMessStringsch
bl affichageMess
b 100f
3: @ end search string not found
ldr r0,iAdrszMessStringNfound
bl affichageMess
100: /* standard end of the program */
mov r0, #0 @ return code
pop {fp,lr} @restaur 2 registers
mov r7, #EXIT @ request to exit program
swi 0 @ perform the system call
iAdrtablesPoi1: .int tablesPoi1
iAdrszMessStringsch: .int szMessStringsch
iAdrszString5: .int szString5
iAdrszStringSch: .int szStringSch
iAdrszStringSch1: .int szStringSch1
iAdrsZoneconv: .int sZoneconv
iAdrszMessStringNfound: .int szMessStringNfound
iAdrszCarriageReturn: .int szCarriageReturn
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {fp,lr} /* save registres */
push {r0,r1,r2,r7} /* save others registers */
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" */
swi #0 /* call systeme */
pop {r0,r1,r2,r7} /* restaur others registers */
pop {fp,lr} /* restaur des 2 registres */
bx lr /* return */
/***************************************************/
/* conversion register signed décimal */
/***************************************************/
/* r0 contient le registre */
/* r1 contient l adresse de la zone de conversion */
conversion10S:
push {r0-r5,lr} /* save des registres */
mov r2,r1 /* debut zone stockage */
mov r5,#'+' /* par defaut le signe est + */
cmp r0,#0 /* nombre négatif ? */
movlt r5,#'-' /* oui le signe est - */
mvnlt r0,r0 /* et inversion en valeur positive */
addlt r0,#1
mov r4,#10 /* longueur de la zone */
1: /* debut de boucle de conversion */
bl divisionpar10 /* division */
add r1,#48 /* ajout de 48 au reste pour conversion ascii */
strb r1,[r2,r4] /* stockage du byte en début de zone r5 + la position r4 */
sub r4,r4,#1 /* position précedente */
cmp r0,#0
bne 1b /* boucle si quotient different de zéro */
strb r5,[r2,r4] /* stockage du signe à la position courante */
subs r4,r4,#1 /* position précedente */
blt 100f /* si r4 < 0 fin */
/* sinon il faut completer le debut de la zone avec des blancs */
mov r3,#' ' /* caractere espace */
2:
strb r3,[r2,r4] /* stockage du byte */
subs r4,r4,#1 /* position précedente */
bge 2b /* boucle si r4 plus grand ou egal a zero */
100: /* fin standard de la fonction */
pop {r0-r5,lr} /*restaur desregistres */
bx lr
/***************************************************/
/* division par 10 signé */
/* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/*
/* and http://www.hackersdelight.org/ */
/***************************************************/
/* r0 contient le dividende */
/* r0 retourne le quotient */
/* r1 retourne le reste */
divisionpar10:
/* r0 contains the argument to be divided by 10 */
push {r2-r4} /* save registers */
mov r4,r0
ldr r3, .Ls_magic_number_10 /* r1 <- magic_number */
smull r1, r2, r3, r0 /* r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) */
mov r2, r2, ASR #2 /* r2 <- r2 >> 2 */
mov r1, r0, LSR #31 /* r1 <- r0 >> 31 */
add r0, r2, r1 /* r0 <- r2 + r1 */
add r2,r0,r0, lsl #2 /* r2 <- r0 * 5 */
sub r1,r4,r2, lsl #1 /* r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) */
pop {r2-r4}
bx lr /* leave function */
bx lr /* leave function */
.Ls_magic_number_10: .word 0x66666667
|
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part", where the imaginary part is the number to be multiplied by
i
{\displaystyle i}
.
Task
Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.)
Print the results for each operation tested.
Optional: Show complex conjugation.
By definition, the complex conjugate of
a
+
b
i
{\displaystyle a+bi}
is
a
−
b
i
{\displaystyle a-bi}
Some languages have complex number libraries available. If your language does, show the operations. If your language does not, also show the definition of this type.
| #C.23 | C# | namespace RosettaCode.Arithmetic.Complex
{
using System;
using System.Numerics;
internal static class Program
{
private static void Main()
{
var number = Complex.ImaginaryOne;
foreach (var result in new[] { number + number, number * number, -number, 1 / number, Complex.Conjugate(number) })
{
Console.WriteLine(result);
}
}
}
} |
http://rosettacode.org/wiki/Arena_storage_pool | Arena storage pool | Dynamically allocated objects take their memory from a heap.
The memory for an object is provided by an allocator which maintains the storage pool used for the heap.
Often a call to allocator is denoted as
P := new T
where T is the type of an allocated object, and P is a reference to the object.
The storage pool chosen by the allocator can be determined by either:
the object type T
the type of pointer P
In the former case objects can be allocated only in one storage pool.
In the latter case objects of the type can be allocated in any storage pool or on the stack.
Task
The task is to show how allocators and user-defined storage pools are supported by the language.
In particular:
define an arena storage pool. An arena is a pool in which objects are allocated individually, but freed by groups.
allocate some objects (e.g., integers) in the pool.
Explain what controls the storage pool choice in the language.
| #Julia | Julia |
matrix = zeros(Float64, (1000,1000,1000))
# use matrix, then when done set variable to 0 to garbage collect the matrix:
matrix = 0 # large memory pool will now be collected when needed
|
http://rosettacode.org/wiki/Arena_storage_pool | Arena storage pool | Dynamically allocated objects take their memory from a heap.
The memory for an object is provided by an allocator which maintains the storage pool used for the heap.
Often a call to allocator is denoted as
P := new T
where T is the type of an allocated object, and P is a reference to the object.
The storage pool chosen by the allocator can be determined by either:
the object type T
the type of pointer P
In the former case objects can be allocated only in one storage pool.
In the latter case objects of the type can be allocated in any storage pool or on the stack.
Task
The task is to show how allocators and user-defined storage pools are supported by the language.
In particular:
define an arena storage pool. An arena is a pool in which objects are allocated individually, but freed by groups.
allocate some objects (e.g., integers) in the pool.
Explain what controls the storage pool choice in the language.
| #Kotlin | Kotlin | // Kotlin Native v0.5
import kotlinx.cinterop.*
fun main(args: Array<String>) {
memScoped {
val intVar1 = alloc<IntVar>()
intVar1.value = 1
val intVar2 = alloc<IntVar>()
intVar2.value = 2
println("${intVar1.value} + ${intVar2.value} = ${intVar1.value + intVar2.value}")
}
// native memory used by intVar1 & intVar2 is automatically freed when memScoped block ends
} |
http://rosettacode.org/wiki/Arena_storage_pool | Arena storage pool | Dynamically allocated objects take their memory from a heap.
The memory for an object is provided by an allocator which maintains the storage pool used for the heap.
Often a call to allocator is denoted as
P := new T
where T is the type of an allocated object, and P is a reference to the object.
The storage pool chosen by the allocator can be determined by either:
the object type T
the type of pointer P
In the former case objects can be allocated only in one storage pool.
In the latter case objects of the type can be allocated in any storage pool or on the stack.
Task
The task is to show how allocators and user-defined storage pools are supported by the language.
In particular:
define an arena storage pool. An arena is a pool in which objects are allocated individually, but freed by groups.
allocate some objects (e.g., integers) in the pool.
Explain what controls the storage pool choice in the language.
| #Lua | Lua | pool = {} -- create an "arena" for the variables a,b,c,d
pool.a = 1 -- individually allocated..
pool.b = "hello"
pool.c = true
pool.d = { 1,2,3 }
pool = nil -- release reference allowing garbage collection of entire structure |
http://rosettacode.org/wiki/Arena_storage_pool | Arena storage pool | Dynamically allocated objects take their memory from a heap.
The memory for an object is provided by an allocator which maintains the storage pool used for the heap.
Often a call to allocator is denoted as
P := new T
where T is the type of an allocated object, and P is a reference to the object.
The storage pool chosen by the allocator can be determined by either:
the object type T
the type of pointer P
In the former case objects can be allocated only in one storage pool.
In the latter case objects of the type can be allocated in any storage pool or on the stack.
Task
The task is to show how allocators and user-defined storage pools are supported by the language.
In particular:
define an arena storage pool. An arena is a pool in which objects are allocated individually, but freed by groups.
allocate some objects (e.g., integers) in the pool.
Explain what controls the storage pool choice in the language.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | f[x_] := x^2 |
http://rosettacode.org/wiki/Arithmetic/Rational | Arithmetic/Rational | Task
Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language.
Example
Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number).
Further define the appropriate rational unary operators abs and '-', with the binary operators for addition '+', subtraction '-', multiplication '×', division '/', integer division '÷', modulo division, the comparison operators (e.g. '<', '≤', '>', & '≥') and equality operators (e.g. '=' & '≠').
Define standard coercion operators for casting int to frac etc.
If space allows, define standard increment and decrement operators (e.g. '+:=' & '-:=' etc.).
Finally test the operators:
Use the new type frac to find all perfect numbers less than 219 by summing the reciprocal of the factors.
Related task
Perfect Numbers
| #C.2B.2B | C++ | #include <iostream>
#include "math.h"
#include "boost/rational.hpp"
typedef boost::rational<int> frac;
bool is_perfect(int c)
{
frac sum(1, c);
for (int f = 2;f < sqrt(static_cast<float>(c)); ++f){
if (c % f == 0) sum += frac(1,f) + frac(1, c/f);
}
if (sum.denominator() == 1){
return (sum == 1);
}
return false;
}
int main()
{
for (int candidate = 2; candidate < 0x80000; ++candidate){
if (is_perfect(candidate))
std::cout << candidate << " is perfect" << std::endl;
}
return 0;
} |
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geometric mean of two numbers.
The arithmetic-geometric mean of two numbers can be (usefully) denoted as
a
g
m
(
a
,
g
)
{\displaystyle \mathrm {agm} (a,g)}
, and is equal to the limit of the sequence:
a
0
=
a
;
g
0
=
g
{\displaystyle a_{0}=a;\qquad g_{0}=g}
a
n
+
1
=
1
2
(
a
n
+
g
n
)
;
g
n
+
1
=
a
n
g
n
.
{\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.}
Since the limit of
a
n
−
g
n
{\displaystyle a_{n}-g_{n}}
tends (rapidly) to zero with iterations, this is an efficient method.
Demonstrate the function by calculating:
a
g
m
(
1
,
1
/
2
)
{\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})}
Also see
mathworld.wolfram.com/Arithmetic-Geometric Mean
| #BQN | BQN | AGM ← {
(|𝕨-𝕩) ≤ 1e¯15? 𝕨;
(0.5×𝕨+𝕩) 𝕊 √𝕨×𝕩
}
1 AGM 1÷√2 |
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geometric mean of two numbers.
The arithmetic-geometric mean of two numbers can be (usefully) denoted as
a
g
m
(
a
,
g
)
{\displaystyle \mathrm {agm} (a,g)}
, and is equal to the limit of the sequence:
a
0
=
a
;
g
0
=
g
{\displaystyle a_{0}=a;\qquad g_{0}=g}
a
n
+
1
=
1
2
(
a
n
+
g
n
)
;
g
n
+
1
=
a
n
g
n
.
{\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.}
Since the limit of
a
n
−
g
n
{\displaystyle a_{n}-g_{n}}
tends (rapidly) to zero with iterations, this is an efficient method.
Demonstrate the function by calculating:
a
g
m
(
1
,
1
/
2
)
{\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})}
Also see
mathworld.wolfram.com/Arithmetic-Geometric Mean
| #C | C | #include<math.h>
#include<stdio.h>
#include<stdlib.h>
double agm( double a, double g ) {
/* arithmetic-geometric mean */
double iota = 1.0E-16;
double a1, g1;
if( a*g < 0.0 ) {
printf( "arithmetic-geometric mean undefined when x*y<0\n" );
exit(1);
}
while( fabs(a-g)>iota ) {
a1 = (a + g) / 2.0;
g1 = sqrt(a * g);
a = a1;
g = g1;
}
return a;
}
int main( void ) {
double x, y;
printf( "Enter two numbers: " );
scanf( "%lf%lf", &x, &y );
printf( "The arithmetic-geometric mean is %lf\n", agm(x, y) );
return 0;
}
|
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Get two integers from the user, and then (for those two integers), display their:
sum
difference
product
integer quotient
remainder
exponentiation (if the operator exists)
Don't include error handling.
For quotient, indicate how it rounds (e.g. towards zero, towards negative infinity, etc.).
For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
| #TI-83_BASIC | TI-83 BASIC |
Prompt A,B
Disp "SUM"
Pause A+B
Disp "DIFFERENCE"
Pause A-B
Disp "PRODUCT"
Pause AB
Disp "INTEGER QUOTIENT"
Pause int(A/B)
Disp "REMAINDER"
Pause A-B*int(A/B)
|
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Get two integers from the user, and then (for those two integers), display their:
sum
difference
product
integer quotient
remainder
exponentiation (if the operator exists)
Don't include error handling.
For quotient, indicate how it rounds (e.g. towards zero, towards negative infinity, etc.).
For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
| #TI-89_BASIC | TI-89 BASIC | Local a, b
Prompt a, b
Disp "Sum: " & string(a + b)
Disp "Difference: " & string(a - b)
Disp "Product: " & string(a * b)
Disp "Integer quotient: " & string(intDiv(a, b))
Disp "Remainder: " & string(remain(a, b)) |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #360_Assembly | 360 Assembly | * 100 doors 13/08/2015
HUNDOOR CSECT
USING HUNDOOR,R12
LR R12,R15
LA R6,0
LA R8,1 step 1
LA R9,100
LOOPI BXH R6,R8,ELOOPI do ipass=1 to 100 (R6)
LR R7,R6
SR R7,R6
LR R10,R6 step ipass
LA R11,100
LOOPJ BXH R7,R10,ELOOPJ do idoor=ipass to 100 by ipass (R7)
LA R5,DOORS-1
AR R5,R7
XI 0(R5),X'01' doors(idoor)=not(doors(idoor))
NEXTJ B LOOPJ
ELOOPJ B LOOPI
ELOOPI LA R10,BUFFER R10 address of the buffer
LA R5,DOORS R5 address of doors item
LA R6,1 idoor=1 (R6)
LA R9,100 loop counter
LOOPN CLI 0(R5),X'01' if doors(idoor)=1
BNE NEXTN
XDECO R6,XDEC idoor to decimal
MVC 0(4,R10),XDEC+8 move decimal to buffer
LA R10,4(R10)
NEXTN LA R6,1(R6) idoor=idoor+1
LA R5,1(R5)
BCT R9,LOOPN loop
ELOOPN XPRNT BUFFER,80
RETURN XR R15,R15
BR R14
DOORS DC 100X'00'
BUFFER DC CL80' '
XDEC DS CL12
YREGS
END HUNDOOR |
http://rosettacode.org/wiki/Arithmetic-geometric_mean/Calculate_Pi | Arithmetic-geometric mean/Calculate Pi | Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate
π
{\displaystyle \pi }
.
With the same notations used in Arithmetic-geometric mean, we can summarize the paper by writing:
π
=
4
a
g
m
(
1
,
1
/
2
)
2
1
−
∑
n
=
1
∞
2
n
+
1
(
a
n
2
−
g
n
2
)
{\displaystyle \pi ={\frac {4\;\mathrm {agm} (1,1/{\sqrt {2}})^{2}}{1-\sum \limits _{n=1}^{\infty }2^{n+1}(a_{n}^{2}-g_{n}^{2})}}}
This allows you to make the approximation, for any large N:
π
≈
4
a
N
2
1
−
∑
k
=
1
N
2
k
+
1
(
a
k
2
−
g
k
2
)
{\displaystyle \pi \approx {\frac {4\;a_{N}^{2}}{1-\sum \limits _{k=1}^{N}2^{k+1}(a_{k}^{2}-g_{k}^{2})}}}
The purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of
π
{\displaystyle \pi }
.
| #PARI.2FGP | PARI/GP | pi(n)=my(a=1,g=2^-.5);(1-2*sum(k=1,n,[a,g]=[(a+g)/2,sqrt(a*g)];(a^2-g^2)<<k))^-1*4*a^2
pi(6) |
http://rosettacode.org/wiki/Arithmetic-geometric_mean/Calculate_Pi | Arithmetic-geometric mean/Calculate Pi | Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate
π
{\displaystyle \pi }
.
With the same notations used in Arithmetic-geometric mean, we can summarize the paper by writing:
π
=
4
a
g
m
(
1
,
1
/
2
)
2
1
−
∑
n
=
1
∞
2
n
+
1
(
a
n
2
−
g
n
2
)
{\displaystyle \pi ={\frac {4\;\mathrm {agm} (1,1/{\sqrt {2}})^{2}}{1-\sum \limits _{n=1}^{\infty }2^{n+1}(a_{n}^{2}-g_{n}^{2})}}}
This allows you to make the approximation, for any large N:
π
≈
4
a
N
2
1
−
∑
k
=
1
N
2
k
+
1
(
a
k
2
−
g
k
2
)
{\displaystyle \pi \approx {\frac {4\;a_{N}^{2}}{1-\sum \limits _{k=1}^{N}2^{k+1}(a_{k}^{2}-g_{k}^{2})}}}
The purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of
π
{\displaystyle \pi }
.
| #Perl | Perl | use Math::BigFloat try => "GMP,Pari";
my $digits = shift || 100; # Get number of digits from command line
print agm_pi($digits), "\n";
sub agm_pi {
my $digits = shift;
my $acc = $digits + 8;
my $HALF = Math::BigFloat->new("0.5");
my ($an, $bn, $tn, $pn) = (Math::BigFloat->bone, $HALF->copy->bsqrt($acc),
$HALF->copy->bmul($HALF), Math::BigFloat->bone);
while ($pn < $acc) {
my $prev_an = $an->copy;
$an->badd($bn)->bmul($HALF, $acc);
$bn->bmul($prev_an)->bsqrt($acc);
$prev_an->bsub($an);
$tn->bsub($pn * $prev_an * $prev_an);
$pn->badd($pn);
}
$an->badd($bn);
$an->bmul($an,$acc)->bdiv(4*$tn, $digits);
return $an;
} |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #Arturo | Arturo | ; empty array
arrA: []
; array with initial values
arrB: ["one" "two" "three"]
; adding an element to an existing array
arrB: arrB ++ "four"
print arrB
; another way to add an element
append 'arrB "five"
print arrB
; retrieve an element at some index
print arrB\1 |
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part", where the imaginary part is the number to be multiplied by
i
{\displaystyle i}
.
Task
Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.)
Print the results for each operation tested.
Optional: Show complex conjugation.
By definition, the complex conjugate of
a
+
b
i
{\displaystyle a+bi}
is
a
−
b
i
{\displaystyle a-bi}
Some languages have complex number libraries available. If your language does, show the operations. If your language does not, also show the definition of this type.
| #C.2B.2B | C++ | #include <iostream>
#include <complex>
using std::complex;
void complex_operations() {
complex<double> a(1.0, 1.0);
complex<double> b(3.14159, 1.25);
// addition
std::cout << a + b << std::endl;
// multiplication
std::cout << a * b << std::endl;
// inversion
std::cout << 1.0 / a << std::endl;
// negation
std::cout << -a << std::endl;
// conjugate
std::cout << std::conj(a) << std::endl;
} |
http://rosettacode.org/wiki/Arena_storage_pool | Arena storage pool | Dynamically allocated objects take their memory from a heap.
The memory for an object is provided by an allocator which maintains the storage pool used for the heap.
Often a call to allocator is denoted as
P := new T
where T is the type of an allocated object, and P is a reference to the object.
The storage pool chosen by the allocator can be determined by either:
the object type T
the type of pointer P
In the former case objects can be allocated only in one storage pool.
In the latter case objects of the type can be allocated in any storage pool or on the stack.
Task
The task is to show how allocators and user-defined storage pools are supported by the language.
In particular:
define an arena storage pool. An arena is a pool in which objects are allocated individually, but freed by groups.
allocate some objects (e.g., integers) in the pool.
Explain what controls the storage pool choice in the language.
| #Nim | Nim |
####################################################################################################
# Pool management.
# Pool of objects.
type
Block[Size: static Positive, T] = ref array[Size, T]
Pool[BlockSize: static Positive, T] = ref object
blocks: seq[Block[BlockSize, T]] # List of blocks.
lastindex: int # Last object index in the last block.
#---------------------------------------------------------------------------------------------------
proc newPool(S: static Positive; T: typedesc): Pool[S, T] =
## Create a pool with blocks of "S" type "T" objects.
new(result)
result.blocks = @[new(Block[S, T])]
result.lastindex = -1
#---------------------------------------------------------------------------------------------------
proc getItem(pool: Pool): ptr pool.T =
## Return a pointer on a node from the pool.
inc pool.lastindex
if pool.lastindex == pool.BlockSize:
# Allocate a new block. It is initialized with zeroes.
pool.blocks.add(new(Block[pool.BlockSize, pool.T]))
pool.lastindex = 0
result = cast[ptr pool.T](addr(pool.blocks[^1][pool.lastindex]))
####################################################################################################
# Example: use the pool to allocate nodes.
type
# Node description.
NodePtr = ptr Node
Node = object
value: int
prev: NodePtr
next: NodePtr
type NodePool = Pool[5000, Node]
proc newNode(pool: NodePool; value: int): NodePtr =
## Create a new node.
result = pool.getItem()
result.value = value
result.prev = nil # Not needed, allocated memory being initialized to 0.
result.next = nil
proc test() =
## Build a circular list of nodes managed in a pool.
let pool = newPool(NodePool.BlockSize, Node)
var head = pool.newNode(0)
var prev = head
for i in 1..11999:
let node = pool.newNode(i)
node.prev = prev
prev.next = node
# Display information about the pool state.
echo "Number of allocated blocks: ", pool.blocks.len
echo "Number of nodes in the last block: ", pool.lastindex + 1
test()
# No need to free the pool. This is done automatically as it has been allocated by "new". |
http://rosettacode.org/wiki/Arena_storage_pool | Arena storage pool | Dynamically allocated objects take their memory from a heap.
The memory for an object is provided by an allocator which maintains the storage pool used for the heap.
Often a call to allocator is denoted as
P := new T
where T is the type of an allocated object, and P is a reference to the object.
The storage pool chosen by the allocator can be determined by either:
the object type T
the type of pointer P
In the former case objects can be allocated only in one storage pool.
In the latter case objects of the type can be allocated in any storage pool or on the stack.
Task
The task is to show how allocators and user-defined storage pools are supported by the language.
In particular:
define an arena storage pool. An arena is a pool in which objects are allocated individually, but freed by groups.
allocate some objects (e.g., integers) in the pool.
Explain what controls the storage pool choice in the language.
| #Oforth | Oforth | Object Class new: MyClass(a, b, c)
MyClass new |
http://rosettacode.org/wiki/Arena_storage_pool | Arena storage pool | Dynamically allocated objects take their memory from a heap.
The memory for an object is provided by an allocator which maintains the storage pool used for the heap.
Often a call to allocator is denoted as
P := new T
where T is the type of an allocated object, and P is a reference to the object.
The storage pool chosen by the allocator can be determined by either:
the object type T
the type of pointer P
In the former case objects can be allocated only in one storage pool.
In the latter case objects of the type can be allocated in any storage pool or on the stack.
Task
The task is to show how allocators and user-defined storage pools are supported by the language.
In particular:
define an arena storage pool. An arena is a pool in which objects are allocated individually, but freed by groups.
allocate some objects (e.g., integers) in the pool.
Explain what controls the storage pool choice in the language.
| #ooRexx | ooRexx |
'==============
Class ArenaPool
'==============
string buf
sys pb,ii
method Setup(sys n) as sys {buf=nuls n : pb=strptr buf : ii=0 : return pb}
method Alloc(sys n) as sys {method=pb+ii : ii+=n}
method Empty() {buf="" : pb=0 : ii=0}
end class
macro Create(type,name,qty,pool)
type name[qty] at (pool##.alloc qty * sizeof type)
end macro
'====
'DEMO
'====
ArenaPool pool : pool.setup 1000 * sizeof int
Create int,i,100,pool
Create int,j,100,pool
j[51] <= 1,2,3,4,5
print j[51] j[52] j[53] j[54] j[55] 'result 15
pool.empty
|
http://rosettacode.org/wiki/Arena_storage_pool | Arena storage pool | Dynamically allocated objects take their memory from a heap.
The memory for an object is provided by an allocator which maintains the storage pool used for the heap.
Often a call to allocator is denoted as
P := new T
where T is the type of an allocated object, and P is a reference to the object.
The storage pool chosen by the allocator can be determined by either:
the object type T
the type of pointer P
In the former case objects can be allocated only in one storage pool.
In the latter case objects of the type can be allocated in any storage pool or on the stack.
Task
The task is to show how allocators and user-defined storage pools are supported by the language.
In particular:
define an arena storage pool. An arena is a pool in which objects are allocated individually, but freed by groups.
allocate some objects (e.g., integers) in the pool.
Explain what controls the storage pool choice in the language.
| #OxygenBasic | OxygenBasic |
'==============
Class ArenaPool
'==============
string buf
sys pb,ii
method Setup(sys n) as sys {buf=nuls n : pb=strptr buf : ii=0 : return pb}
method Alloc(sys n) as sys {method=pb+ii : ii+=n}
method Empty() {buf="" : pb=0 : ii=0}
end class
macro Create(type,name,qty,pool)
type name[qty] at (pool##.alloc qty * sizeof type)
end macro
'====
'DEMO
'====
ArenaPool pool : pool.setup 1000 * sizeof int
Create int,i,100,pool
Create int,j,100,pool
j[51] <= 1,2,3,4,5
print j[51] j[52] j[53] j[54] j[55] 'result 15
pool.empty
|
http://rosettacode.org/wiki/Arithmetic/Rational | Arithmetic/Rational | Task
Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language.
Example
Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number).
Further define the appropriate rational unary operators abs and '-', with the binary operators for addition '+', subtraction '-', multiplication '×', division '/', integer division '÷', modulo division, the comparison operators (e.g. '<', '≤', '>', & '≥') and equality operators (e.g. '=' & '≠').
Define standard coercion operators for casting int to frac etc.
If space allows, define standard increment and decrement operators (e.g. '+:=' & '-:=' etc.).
Finally test the operators:
Use the new type frac to find all perfect numbers less than 219 by summing the reciprocal of the factors.
Related task
Perfect Numbers
| #Clojure | Clojure | user> 22/7
22/7
user> 34/2
17
user> (+ 37/5 42/9)
181/15 |
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geometric mean of two numbers.
The arithmetic-geometric mean of two numbers can be (usefully) denoted as
a
g
m
(
a
,
g
)
{\displaystyle \mathrm {agm} (a,g)}
, and is equal to the limit of the sequence:
a
0
=
a
;
g
0
=
g
{\displaystyle a_{0}=a;\qquad g_{0}=g}
a
n
+
1
=
1
2
(
a
n
+
g
n
)
;
g
n
+
1
=
a
n
g
n
.
{\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.}
Since the limit of
a
n
−
g
n
{\displaystyle a_{n}-g_{n}}
tends (rapidly) to zero with iterations, this is an efficient method.
Demonstrate the function by calculating:
a
g
m
(
1
,
1
/
2
)
{\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})}
Also see
mathworld.wolfram.com/Arithmetic-Geometric Mean
| #C.23 | C# | namespace RosettaCode.ArithmeticGeometricMean
{
using System;
using System.Collections.Generic;
using System.Globalization;
internal static class Program
{
private static double ArithmeticGeometricMean(double number,
double otherNumber,
IEqualityComparer<double>
comparer)
{
return comparer.Equals(number, otherNumber)
? number
: ArithmeticGeometricMean(
ArithmeticMean(number, otherNumber),
GeometricMean(number, otherNumber), comparer);
}
private static double ArithmeticMean(double number, double otherNumber)
{
return 0.5 * (number + otherNumber);
}
private static double GeometricMean(double number, double otherNumber)
{
return Math.Sqrt(number * otherNumber);
}
private static void Main()
{
Console.WriteLine(
ArithmeticGeometricMean(1, 0.5 * Math.Sqrt(2),
new RelativeDifferenceComparer(1e-5)).
ToString(CultureInfo.InvariantCulture));
}
private class RelativeDifferenceComparer : IEqualityComparer<double>
{
private readonly double _maximumRelativeDifference;
internal RelativeDifferenceComparer(double maximumRelativeDifference)
{
_maximumRelativeDifference = maximumRelativeDifference;
}
public bool Equals(double number, double otherNumber)
{
return RelativeDifference(number, otherNumber) <=
_maximumRelativeDifference;
}
public int GetHashCode(double number)
{
return number.GetHashCode();
}
private static double RelativeDifference(double number,
double otherNumber)
{
return AbsoluteDifference(number, otherNumber) /
Norm(number, otherNumber);
}
private static double AbsoluteDifference(double number,
double otherNumber)
{
return Math.Abs(number - otherNumber);
}
private static double Norm(double number, double otherNumber)
{
return 0.5 * (Math.Abs(number) + Math.Abs(otherNumber));
}
}
}
} |
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Get two integers from the user, and then (for those two integers), display their:
sum
difference
product
integer quotient
remainder
exponentiation (if the operator exists)
Don't include error handling.
For quotient, indicate how it rounds (e.g. towards zero, towards negative infinity, etc.).
For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
| #Toka | Toka | [ ( a b -- )
2dup ." a+b = " + . cr
2dup ." a-b = " - . cr
2dup ." a*b = " * . cr
2dup ." a/b = " / . ." remainder " mod . cr
] is mathops |
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Get two integers from the user, and then (for those two integers), display their:
sum
difference
product
integer quotient
remainder
exponentiation (if the operator exists)
Don't include error handling.
For quotient, indicate how it rounds (e.g. towards zero, towards negative infinity, etc.).
For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
| #TUSCRIPT | TUSCRIPT |
$$ MODE TUSCRIPT
a=5
b=3
c=a+b
c=a-b
c=a*b
c=a/b
c=a%b
|
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #4DOS_Batch | 4DOS Batch |
@echo off
set doors=%@repeat[C,100]
do step = 1 to 100
do door = %step to 100 by %step
set doors=%@left[%@eval[%door-1],%doors]%@if[%@instr[%@eval[%door-1],1,%doors]==C,O,C]%@right[%@eval[100-%door],%doors]
enddo
enddo
|
http://rosettacode.org/wiki/Arithmetic-geometric_mean/Calculate_Pi | Arithmetic-geometric mean/Calculate Pi | Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate
π
{\displaystyle \pi }
.
With the same notations used in Arithmetic-geometric mean, we can summarize the paper by writing:
π
=
4
a
g
m
(
1
,
1
/
2
)
2
1
−
∑
n
=
1
∞
2
n
+
1
(
a
n
2
−
g
n
2
)
{\displaystyle \pi ={\frac {4\;\mathrm {agm} (1,1/{\sqrt {2}})^{2}}{1-\sum \limits _{n=1}^{\infty }2^{n+1}(a_{n}^{2}-g_{n}^{2})}}}
This allows you to make the approximation, for any large N:
π
≈
4
a
N
2
1
−
∑
k
=
1
N
2
k
+
1
(
a
k
2
−
g
k
2
)
{\displaystyle \pi \approx {\frac {4\;a_{N}^{2}}{1-\sum \limits _{k=1}^{N}2^{k+1}(a_{k}^{2}-g_{k}^{2})}}}
The purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of
π
{\displaystyle \pi }
.
| #Phix | Phix | with javascript_semantics
requires("1.0.0") -- (mpfr_set_default_prec[ision] has been renamed)
include mpfr.e
mpfr_set_default_precision(-200) -- set precision to 200 decimal places
mpfr a = mpfr_init(1),
n = mpfr_init(1),
g = mpfr_init(1),
z = mpfr_init(0.25),
half = mpfr_init(0.5),
x1 = mpfr_init(2),
x2 = mpfr_init(),
v = mpfr_init()
mpfr_sqrt(x1,x1)
mpfr_div(g,g,x1) -- g:= 1/sqrt(2)
string prev, curr
for i=1 to 18 do
mpfr_add(x1,a,g)
mpfr_mul(x1,x1,half)
mpfr_mul(x2,a,g)
mpfr_sqrt(x2,x2)
mpfr_sub(v,x1,a)
mpfr_mul(v,v,v)
mpfr_mul(v,v,n)
mpfr_sub(z,z,v)
mpfr_add(n,n,n)
mpfr_set(a,x1)
mpfr_set(g,x2)
mpfr_mul(v,a,a)
mpfr_div(v,v,z)
curr = mpfr_get_fixed(v,200)
if i>1 then
if curr=prev then exit end if
for j=3 to length(curr) do
if prev[j]!=curr[j] then
printf(1,"iteration %d matches previous to %d places\n",{i,j-3})
exit
end if
end for
end if
prev = curr
end for
if curr=prev then
printf(1,"identical result to last iteration:\n%s\n",{curr})
else
printf(1,"insufficient iterations\n")
end if
|
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #AutoHotkey | AutoHotkey | myArray := Object() ; could use JSON-syntax sugar like {key: value}
myArray[1] := "foo"
myArray[2] := "bar"
MsgBox % myArray[2]
; Push a value onto the array
myArray.Insert("baz") |
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part", where the imaginary part is the number to be multiplied by
i
{\displaystyle i}
.
Task
Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.)
Print the results for each operation tested.
Optional: Show complex conjugation.
By definition, the complex conjugate of
a
+
b
i
{\displaystyle a+bi}
is
a
−
b
i
{\displaystyle a-bi}
Some languages have complex number libraries available. If your language does, show the operations. If your language does not, also show the definition of this type.
| #Clojure | Clojure | (ns rosettacode.arithmetic.cmplx
(:require [clojure.algo.generic.arithmetic :as ga])
(:import [java.lang Number]))
(defrecord Complex [^Number r ^Number i]
Object
(toString [{:keys [r i]}]
(apply str
(cond
(zero? r) [(if (= i 1) "" i) "i"]
(zero? i) [r]
:else [r (if (neg? i) "-" "+") i "i"]))))
(defmethod ga/+ [Complex Complex]
[x y] (map->Complex (merge-with + x y)))
(defmethod ga/+ [Complex Number] ; reals become y + 0i
[{:keys [r i]} y] (->Complex (+ r y) i))
(defmethod ga/- Complex
[x] (->> x vals (map -) (apply ->Complex)))
(defmethod ga/* [Complex Complex]
[x y] (map->Complex (merge-with * x y)))
(defmethod ga/* [Complex Number]
[{:keys [r i]} y] (->Complex (* r y) (* i y)))
(ga/defmethod* ga / Complex
[x] (->> x vals (map /) (apply ->Complex)))
(defn conj [^Complex {:keys [r i]}]
(->Complex r (- i)))
(defn inv [^Complex {:keys [r i]}]
(let [m (+ (* r r) (* i i))]
(->Complex (/ r m) (- (/ i m)))))
|
http://rosettacode.org/wiki/Arena_storage_pool | Arena storage pool | Dynamically allocated objects take their memory from a heap.
The memory for an object is provided by an allocator which maintains the storage pool used for the heap.
Often a call to allocator is denoted as
P := new T
where T is the type of an allocated object, and P is a reference to the object.
The storage pool chosen by the allocator can be determined by either:
the object type T
the type of pointer P
In the former case objects can be allocated only in one storage pool.
In the latter case objects of the type can be allocated in any storage pool or on the stack.
Task
The task is to show how allocators and user-defined storage pools are supported by the language.
In particular:
define an arena storage pool. An arena is a pool in which objects are allocated individually, but freed by groups.
allocate some objects (e.g., integers) in the pool.
Explain what controls the storage pool choice in the language.
| #PARI.2FGP | PARI/GP | pari_init(1<<20, 0); // Initialize PARI with a stack size of 1 MB.
GEN four = addii(gen_2, gen_2); // On the stack
GEN persist = gclone(four); // On the heap |
http://rosettacode.org/wiki/Arena_storage_pool | Arena storage pool | Dynamically allocated objects take their memory from a heap.
The memory for an object is provided by an allocator which maintains the storage pool used for the heap.
Often a call to allocator is denoted as
P := new T
where T is the type of an allocated object, and P is a reference to the object.
The storage pool chosen by the allocator can be determined by either:
the object type T
the type of pointer P
In the former case objects can be allocated only in one storage pool.
In the latter case objects of the type can be allocated in any storage pool or on the stack.
Task
The task is to show how allocators and user-defined storage pools are supported by the language.
In particular:
define an arena storage pool. An arena is a pool in which objects are allocated individually, but freed by groups.
allocate some objects (e.g., integers) in the pool.
Explain what controls the storage pool choice in the language.
| #Pascal | Pascal | procedure New (var P: Pointer); |
http://rosettacode.org/wiki/Arena_storage_pool | Arena storage pool | Dynamically allocated objects take their memory from a heap.
The memory for an object is provided by an allocator which maintains the storage pool used for the heap.
Often a call to allocator is denoted as
P := new T
where T is the type of an allocated object, and P is a reference to the object.
The storage pool chosen by the allocator can be determined by either:
the object type T
the type of pointer P
In the former case objects can be allocated only in one storage pool.
In the latter case objects of the type can be allocated in any storage pool or on the stack.
Task
The task is to show how allocators and user-defined storage pools are supported by the language.
In particular:
define an arena storage pool. An arena is a pool in which objects are allocated individually, but freed by groups.
allocate some objects (e.g., integers) in the pool.
Explain what controls the storage pool choice in the language.
| #Phix | Phix | without js
atom mem = allocate(size,true)
|
http://rosettacode.org/wiki/Arena_storage_pool | Arena storage pool | Dynamically allocated objects take their memory from a heap.
The memory for an object is provided by an allocator which maintains the storage pool used for the heap.
Often a call to allocator is denoted as
P := new T
where T is the type of an allocated object, and P is a reference to the object.
The storage pool chosen by the allocator can be determined by either:
the object type T
the type of pointer P
In the former case objects can be allocated only in one storage pool.
In the latter case objects of the type can be allocated in any storage pool or on the stack.
Task
The task is to show how allocators and user-defined storage pools are supported by the language.
In particular:
define an arena storage pool. An arena is a pool in which objects are allocated individually, but freed by groups.
allocate some objects (e.g., integers) in the pool.
Explain what controls the storage pool choice in the language.
| #PicoLisp | PicoLisp |
(malloc 1000 'raw) ; raw allocation, bypass the GC, requires free()-ing
(malloc 1000 'uncollectable) ; no GC, for use with other GCs that Racket can be configured with
(malloc 1000 'atomic) ; a block of memory without internal pointers
(malloc 1000 'nonatomic) ; a block of pointers
(malloc 1000 'eternal) ; uncollectable & atomic, similar to raw malloc but no freeing
(malloc 1000 'stubborn) ; can be declared immutable when mutation is done
(malloc 1000 'interior) ; allocate an immovable block with possible pointers into it
(malloc 1000 'atomic-interior) ; same for atomic chunks
(malloc-immobile-cell v) ; allocates a single cell that the GC will not move
|
http://rosettacode.org/wiki/Arithmetic/Rational | Arithmetic/Rational | Task
Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language.
Example
Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number).
Further define the appropriate rational unary operators abs and '-', with the binary operators for addition '+', subtraction '-', multiplication '×', division '/', integer division '÷', modulo division, the comparison operators (e.g. '<', '≤', '>', & '≥') and equality operators (e.g. '=' & '≠').
Define standard coercion operators for casting int to frac etc.
If space allows, define standard increment and decrement operators (e.g. '+:=' & '-:=' etc.).
Finally test the operators:
Use the new type frac to find all perfect numbers less than 219 by summing the reciprocal of the factors.
Related task
Perfect Numbers
| #Common_Lisp | Common Lisp | (loop for candidate from 2 below (expt 2 19)
for sum = (+ (/ candidate)
(loop for factor from 2 to (isqrt candidate)
when (zerop (mod candidate factor))
sum (+ (/ factor) (/ (floor candidate factor)))))
when (= sum 1)
collect candidate) |
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geometric mean of two numbers.
The arithmetic-geometric mean of two numbers can be (usefully) denoted as
a
g
m
(
a
,
g
)
{\displaystyle \mathrm {agm} (a,g)}
, and is equal to the limit of the sequence:
a
0
=
a
;
g
0
=
g
{\displaystyle a_{0}=a;\qquad g_{0}=g}
a
n
+
1
=
1
2
(
a
n
+
g
n
)
;
g
n
+
1
=
a
n
g
n
.
{\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.}
Since the limit of
a
n
−
g
n
{\displaystyle a_{n}-g_{n}}
tends (rapidly) to zero with iterations, this is an efficient method.
Demonstrate the function by calculating:
a
g
m
(
1
,
1
/
2
)
{\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})}
Also see
mathworld.wolfram.com/Arithmetic-Geometric Mean
| #C.2B.2B | C++ |
#include<bits/stdc++.h>
using namespace std;
#define _cin ios_base::sync_with_stdio(0); cin.tie(0);
#define rep(a, b) for(ll i =a;i<=b;++i)
double agm(double a, double g) //ARITHMETIC GEOMETRIC MEAN
{ double epsilon = 1.0E-16,a1,g1;
if(a*g<0.0)
{ cout<<"Couldn't find arithmetic-geometric mean of these numbers\n";
exit(1);
}
while(fabs(a-g)>epsilon)
{ a1 = (a+g)/2.0;
g1 = sqrt(a*g);
a = a1;
g = g1;
}
return a;
}
int main()
{ _cin; //fast input-output
double x, y;
cout<<"Enter X and Y: "; //Enter two numbers
cin>>x>>y;
cout<<"\nThe Arithmetic-Geometric Mean of "<<x<<" and "<<y<<" is "<<agm(x, y);
return 0;
}
|
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geometric mean of two numbers.
The arithmetic-geometric mean of two numbers can be (usefully) denoted as
a
g
m
(
a
,
g
)
{\displaystyle \mathrm {agm} (a,g)}
, and is equal to the limit of the sequence:
a
0
=
a
;
g
0
=
g
{\displaystyle a_{0}=a;\qquad g_{0}=g}
a
n
+
1
=
1
2
(
a
n
+
g
n
)
;
g
n
+
1
=
a
n
g
n
.
{\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.}
Since the limit of
a
n
−
g
n
{\displaystyle a_{n}-g_{n}}
tends (rapidly) to zero with iterations, this is an efficient method.
Demonstrate the function by calculating:
a
g
m
(
1
,
1
/
2
)
{\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})}
Also see
mathworld.wolfram.com/Arithmetic-Geometric Mean
| #Clojure | Clojure | (ns agmcompute
(:gen-class))
; Java Arbitray Precision Library
(import '(org.apfloat Apfloat ApfloatMath))
(def precision 70)
(def one (Apfloat. 1M precision))
(def two (Apfloat. 2M precision))
(def half (Apfloat. 0.5M precision))
(def isqrt2 (.divide one (ApfloatMath/pow two half)))
(def TOLERANCE (Apfloat. 0.000000M precision))
(defn agm [a g]
" Simple AGM Loop calculation "
(let [THRESH 1e-65 ; done when error less than threshold or we exceed max loops
MAX-LOOPS 1000000]
(loop [[an gn] [a g], cnt 0]
(if (or (< (ApfloatMath/abs (.subtract an gn)) THRESH)
(> cnt MAX-LOOPS))
an
(recur [(.multiply (.add an gn) half) (ApfloatMath/pow (.multiply an gn) half)]
(inc cnt))))))
(println (agm one isqrt2))
|
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Get two integers from the user, and then (for those two integers), display their:
sum
difference
product
integer quotient
remainder
exponentiation (if the operator exists)
Don't include error handling.
For quotient, indicate how it rounds (e.g. towards zero, towards negative infinity, etc.).
For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
| #UNIX_Shell | UNIX Shell | #!/bin/sh
read a; read b;
echo "a+b = " `expr $a + $b`
echo "a-b = " `expr $a - $b`
echo "a*b = " `expr $a \* $b`
echo "a/b = " `expr $a / $b` # truncates towards 0
echo "a mod b = " `expr $a % $b` # same sign as first operand |
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Get two integers from the user, and then (for those two integers), display their:
sum
difference
product
integer quotient
remainder
exponentiation (if the operator exists)
Don't include error handling.
For quotient, indicate how it rounds (e.g. towards zero, towards negative infinity, etc.).
For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
| #Ursa | Ursa | #
# integer arithmetic
#
decl int x y
out "number 1: " console
set x (in int console)
out "number 2: " console
set y (in int console)
out "\nsum:\t" (int (+ x y)) endl console
out "diff:\t" (int (- x y)) endl console
out "prod:\t" (int (* x y)) endl console
# quotient doesn't round at all, but the int function rounds up
out "quot:\t" (int (/ x y)) endl console
# mod takes the sign of x
out "mod:\t" (int (mod x y)) endl console |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #6502_Assembly | 6502 Assembly | ; 100 DOORS in 6502 assembly language for: http://www.6502asm.com/beta/index.html
; Written for the original MOS Technology, Inc. NMOS version of the 6502, but should work with any version.
; Based on BASIC QB64 unoptimized version: http://rosettacode.org/wiki/100_doors#BASIC
;
; Notes:
; Doors array[1..100] is at $0201..$0264. On the specified emulator, this is in video memory, so tbe results will
; be directly shown as pixels in the display.
; $0200 (door 0) is cleared for display purposes but is not involved in the open/close loops.
; Y register holds Stride
; X register holds Index
; Zero Page address $01 used to add Stride to Index (via A) because there's no add-to-X or add-Y-to-A instruction.
; First, zero door array
LDA #00
LDX #100
Z_LOOP:
STA 200,X
DEX
BNE Z_LOOP
STA 200,X
; Now do doors repeated open/close
LDY #01 ; Initial value of Stride
S_LOOP:
CPY #101
BCS S_DONE
TYA ; Initial value of Index
I_LOOP:
CMP #101
BCS I_DONE
TAX ; Use as Door array index
INC $200,X ; Toggle bit 0 to reverse state of door
STY 01 ; Add stride (Y) to index (X, via A)
ADC 01
BCC I_LOOP
I_DONE:
INY
BNE S_LOOP
S_DONE:
; Finally, format array values for output: 0 for closed, 1 for open
LDX #100
C_LOOP:
LDA $200,X
AND #$01
STA $200,X
DEX
BNE C_LOOP |
http://rosettacode.org/wiki/Arithmetic-geometric_mean/Calculate_Pi | Arithmetic-geometric mean/Calculate Pi | Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate
π
{\displaystyle \pi }
.
With the same notations used in Arithmetic-geometric mean, we can summarize the paper by writing:
π
=
4
a
g
m
(
1
,
1
/
2
)
2
1
−
∑
n
=
1
∞
2
n
+
1
(
a
n
2
−
g
n
2
)
{\displaystyle \pi ={\frac {4\;\mathrm {agm} (1,1/{\sqrt {2}})^{2}}{1-\sum \limits _{n=1}^{\infty }2^{n+1}(a_{n}^{2}-g_{n}^{2})}}}
This allows you to make the approximation, for any large N:
π
≈
4
a
N
2
1
−
∑
k
=
1
N
2
k
+
1
(
a
k
2
−
g
k
2
)
{\displaystyle \pi \approx {\frac {4\;a_{N}^{2}}{1-\sum \limits _{k=1}^{N}2^{k+1}(a_{k}^{2}-g_{k}^{2})}}}
The purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of
π
{\displaystyle \pi }
.
| #PicoLisp | PicoLisp | (scl 40)
(de pi ()
(let
(A 1.0 N 1.0 Z 0.25
G (/ (* 1.0 1.0) (sqrt 2.0 1.0)) )
(use (X1 X2 V)
(do 18
(setq
X1 (/ (* (+ A G) 0.5) 1.0)
X2 (sqrt (* A G))
V (- X1 A)
Z (- Z (/ (* (/ (* V V) 1.0) N) 1.0))
N (+ N N)
A X1
G X2 ) ) )
(round (/ (* A A) Z) 40)) )
(println (pi))
(bye) |
http://rosettacode.org/wiki/Arithmetic-geometric_mean/Calculate_Pi | Arithmetic-geometric mean/Calculate Pi | Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate
π
{\displaystyle \pi }
.
With the same notations used in Arithmetic-geometric mean, we can summarize the paper by writing:
π
=
4
a
g
m
(
1
,
1
/
2
)
2
1
−
∑
n
=
1
∞
2
n
+
1
(
a
n
2
−
g
n
2
)
{\displaystyle \pi ={\frac {4\;\mathrm {agm} (1,1/{\sqrt {2}})^{2}}{1-\sum \limits _{n=1}^{\infty }2^{n+1}(a_{n}^{2}-g_{n}^{2})}}}
This allows you to make the approximation, for any large N:
π
≈
4
a
N
2
1
−
∑
k
=
1
N
2
k
+
1
(
a
k
2
−
g
k
2
)
{\displaystyle \pi \approx {\frac {4\;a_{N}^{2}}{1-\sum \limits _{k=1}^{N}2^{k+1}(a_{k}^{2}-g_{k}^{2})}}}
The purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of
π
{\displaystyle \pi }
.
| #Python | Python | from decimal import *
D = Decimal
getcontext().prec = 100
a = n = D(1)
g, z, half = 1 / D(2).sqrt(), D(0.25), D(0.5)
for i in range(18):
x = [(a + g) * half, (a * g).sqrt()]
var = x[0] - a
z -= var * var * n
n += n
a, g = x
print(a * a / z) |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #AutoIt | AutoIt |
#include <Array.au3> ;Include extended Array functions (_ArrayDisplay)
Local $aInputs[1] ;Create the Array with just 1 element
While True ;Endless loop
$aInputs[UBound($aInputs) - 1] = InputBox("Array", "Add one value") ;Save user input to the last element of the Array
If $aInputs[UBound($aInputs) - 1] = "" Then ;If an empty string is entered, then...
ReDim $aInputs[UBound($aInputs) - 1] ;...remove them from the Array and...
ExitLoop ;... exit the loop!
EndIf
ReDim $aInputs[UBound($aInputs) + 1] ;Add an empty element to the Array
WEnd
_ArrayDisplay($aInputs) ;Display the Array
|
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part", where the imaginary part is the number to be multiplied by
i
{\displaystyle i}
.
Task
Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.)
Print the results for each operation tested.
Optional: Show complex conjugation.
By definition, the complex conjugate of
a
+
b
i
{\displaystyle a+bi}
is
a
−
b
i
{\displaystyle a-bi}
Some languages have complex number libraries available. If your language does, show the operations. If your language does not, also show the definition of this type.
| #COBOL | COBOL | $SET SOURCEFORMAT "FREE"
$SET ILUSING "System"
$SET ILUSING "System.Numerics"
class-id Prog.
method-id. Main static.
procedure division.
declare num as type Complex = type Complex::ImaginaryOne()
declare results as type Complex occurs any
set content of results to ((num + num), (num * num), (- num), (1 / num), type Complex::Conjugate(num))
perform varying result as type Complex thru results
display result
end-perform
end method.
end class. |
http://rosettacode.org/wiki/Arena_storage_pool | Arena storage pool | Dynamically allocated objects take their memory from a heap.
The memory for an object is provided by an allocator which maintains the storage pool used for the heap.
Often a call to allocator is denoted as
P := new T
where T is the type of an allocated object, and P is a reference to the object.
The storage pool chosen by the allocator can be determined by either:
the object type T
the type of pointer P
In the former case objects can be allocated only in one storage pool.
In the latter case objects of the type can be allocated in any storage pool or on the stack.
Task
The task is to show how allocators and user-defined storage pools are supported by the language.
In particular:
define an arena storage pool. An arena is a pool in which objects are allocated individually, but freed by groups.
allocate some objects (e.g., integers) in the pool.
Explain what controls the storage pool choice in the language.
| #PL.2FI | PL/I |
(malloc 1000 'raw) ; raw allocation, bypass the GC, requires free()-ing
(malloc 1000 'uncollectable) ; no GC, for use with other GCs that Racket can be configured with
(malloc 1000 'atomic) ; a block of memory without internal pointers
(malloc 1000 'nonatomic) ; a block of pointers
(malloc 1000 'eternal) ; uncollectable & atomic, similar to raw malloc but no freeing
(malloc 1000 'stubborn) ; can be declared immutable when mutation is done
(malloc 1000 'interior) ; allocate an immovable block with possible pointers into it
(malloc 1000 'atomic-interior) ; same for atomic chunks
(malloc-immobile-cell v) ; allocates a single cell that the GC will not move
|
http://rosettacode.org/wiki/Arena_storage_pool | Arena storage pool | Dynamically allocated objects take their memory from a heap.
The memory for an object is provided by an allocator which maintains the storage pool used for the heap.
Often a call to allocator is denoted as
P := new T
where T is the type of an allocated object, and P is a reference to the object.
The storage pool chosen by the allocator can be determined by either:
the object type T
the type of pointer P
In the former case objects can be allocated only in one storage pool.
In the latter case objects of the type can be allocated in any storage pool or on the stack.
Task
The task is to show how allocators and user-defined storage pools are supported by the language.
In particular:
define an arena storage pool. An arena is a pool in which objects are allocated individually, but freed by groups.
allocate some objects (e.g., integers) in the pool.
Explain what controls the storage pool choice in the language.
| #Python | Python |
(malloc 1000 'raw) ; raw allocation, bypass the GC, requires free()-ing
(malloc 1000 'uncollectable) ; no GC, for use with other GCs that Racket can be configured with
(malloc 1000 'atomic) ; a block of memory without internal pointers
(malloc 1000 'nonatomic) ; a block of pointers
(malloc 1000 'eternal) ; uncollectable & atomic, similar to raw malloc but no freeing
(malloc 1000 'stubborn) ; can be declared immutable when mutation is done
(malloc 1000 'interior) ; allocate an immovable block with possible pointers into it
(malloc 1000 'atomic-interior) ; same for atomic chunks
(malloc-immobile-cell v) ; allocates a single cell that the GC will not move
|
http://rosettacode.org/wiki/Arena_storage_pool | Arena storage pool | Dynamically allocated objects take their memory from a heap.
The memory for an object is provided by an allocator which maintains the storage pool used for the heap.
Often a call to allocator is denoted as
P := new T
where T is the type of an allocated object, and P is a reference to the object.
The storage pool chosen by the allocator can be determined by either:
the object type T
the type of pointer P
In the former case objects can be allocated only in one storage pool.
In the latter case objects of the type can be allocated in any storage pool or on the stack.
Task
The task is to show how allocators and user-defined storage pools are supported by the language.
In particular:
define an arena storage pool. An arena is a pool in which objects are allocated individually, but freed by groups.
allocate some objects (e.g., integers) in the pool.
Explain what controls the storage pool choice in the language.
| #Racket | Racket |
(malloc 1000 'raw) ; raw allocation, bypass the GC, requires free()-ing
(malloc 1000 'uncollectable) ; no GC, for use with other GCs that Racket can be configured with
(malloc 1000 'atomic) ; a block of memory without internal pointers
(malloc 1000 'nonatomic) ; a block of pointers
(malloc 1000 'eternal) ; uncollectable & atomic, similar to raw malloc but no freeing
(malloc 1000 'stubborn) ; can be declared immutable when mutation is done
(malloc 1000 'interior) ; allocate an immovable block with possible pointers into it
(malloc 1000 'atomic-interior) ; same for atomic chunks
(malloc-immobile-cell v) ; allocates a single cell that the GC will not move
|
http://rosettacode.org/wiki/Arena_storage_pool | Arena storage pool | Dynamically allocated objects take their memory from a heap.
The memory for an object is provided by an allocator which maintains the storage pool used for the heap.
Often a call to allocator is denoted as
P := new T
where T is the type of an allocated object, and P is a reference to the object.
The storage pool chosen by the allocator can be determined by either:
the object type T
the type of pointer P
In the former case objects can be allocated only in one storage pool.
In the latter case objects of the type can be allocated in any storage pool or on the stack.
Task
The task is to show how allocators and user-defined storage pools are supported by the language.
In particular:
define an arena storage pool. An arena is a pool in which objects are allocated individually, but freed by groups.
allocate some objects (e.g., integers) in the pool.
Explain what controls the storage pool choice in the language.
| #Raku | Raku | /*REXX doesn't have declarations/allocations of variables, */
/* but this is the closest to an allocation: */
stemmed_array.= 0 /*any undefined element will have this value. */
stemmed_array.1 = '1st entry'
stemmed_array.2 = '2nd entry'
stemmed_array.6000 = 12 ** 2
stemmed_array.dog = stemmed_array.6000 / 2
drop stemmed_array. |
http://rosettacode.org/wiki/Arena_storage_pool | Arena storage pool | Dynamically allocated objects take their memory from a heap.
The memory for an object is provided by an allocator which maintains the storage pool used for the heap.
Often a call to allocator is denoted as
P := new T
where T is the type of an allocated object, and P is a reference to the object.
The storage pool chosen by the allocator can be determined by either:
the object type T
the type of pointer P
In the former case objects can be allocated only in one storage pool.
In the latter case objects of the type can be allocated in any storage pool or on the stack.
Task
The task is to show how allocators and user-defined storage pools are supported by the language.
In particular:
define an arena storage pool. An arena is a pool in which objects are allocated individually, but freed by groups.
allocate some objects (e.g., integers) in the pool.
Explain what controls the storage pool choice in the language.
| #REXX | REXX | /*REXX doesn't have declarations/allocations of variables, */
/* but this is the closest to an allocation: */
stemmed_array.= 0 /*any undefined element will have this value. */
stemmed_array.1 = '1st entry'
stemmed_array.2 = '2nd entry'
stemmed_array.6000 = 12 ** 2
stemmed_array.dog = stemmed_array.6000 / 2
drop stemmed_array. |
http://rosettacode.org/wiki/Arithmetic/Rational | Arithmetic/Rational | Task
Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language.
Example
Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number).
Further define the appropriate rational unary operators abs and '-', with the binary operators for addition '+', subtraction '-', multiplication '×', division '/', integer division '÷', modulo division, the comparison operators (e.g. '<', '≤', '>', & '≥') and equality operators (e.g. '=' & '≠').
Define standard coercion operators for casting int to frac etc.
If space allows, define standard increment and decrement operators (e.g. '+:=' & '-:=' etc.).
Finally test the operators:
Use the new type frac to find all perfect numbers less than 219 by summing the reciprocal of the factors.
Related task
Perfect Numbers
| #D | D | import std.bigint, std.traits, std.conv;
// std.numeric.gcd doesn't work with BigInt.
T gcd(T)(in T a, in T b) pure nothrow {
return (b != 0) ? gcd(b, a % b) : (a < 0) ? -a : a;
}
T lcm(T)(in T a, in T b) pure nothrow {
return a / gcd(a, b) * b;
}
struct RationalT(T) if (!isUnsigned!T) {
private T num, den; // Numerator & denominator.
private enum Type { NegINF = -2,
NegDEN = -1,
NaRAT = 0,
NORMAL = 1,
PosINF = 2 };
this(U : RationalT)(U n) pure nothrow {
num = n.num;
den = n.den;
}
this(U)(in U n) pure nothrow if (isIntegral!U) {
num = toT(n);
den = 1UL;
}
this(U, V)(in U n, in V d) pure nothrow {
num = toT(n);
den = toT(d);
const common = gcd(num, den);
if (common != 0) {
num /= common;
den /= common;
} else { // infinite or NOT a Number
num = (num == 0) ? 0 : (num < 0) ? -1 : 1;
den = 0;
}
if (den < 0) { // Assure den is non-negative.
num = -num;
den = -den;
}
}
static T toT(U)(in ref U n) pure nothrow if (is(U == T)) {
return n;
}
static T toT(U)(in ref U n) pure nothrow if (!is(U == T)) {
T result = n;
return result;
}
T numerator() const pure nothrow @property {
return num;
}
T denominator() const pure nothrow @property {
return den;
}
string toString() const /*pure nothrow*/ {
if (den != 0)
return num.text ~ (den == 1 ? "" : "/" ~ den.text);
if (num == 0)
return "NaRat";
else
return ((num < 0) ? "-" : "+") ~ "infRat";
}
real toReal() pure const nothrow {
static if (is(T == BigInt))
return num.toLong / real(den.toLong);
else
return num / real(den);
}
RationalT opBinary(string op)(in RationalT r)
const pure nothrow if (op == "+" || op == "-") {
T common = lcm(den, r.den);
T n = mixin("common / den * num" ~ op ~
"common / r.den * r.num" );
return RationalT(n, common);
}
RationalT opBinary(string op)(in RationalT r)
const pure nothrow if (op == "*") {
return RationalT(num * r.num, den * r.den);
}
RationalT opBinary(string op)(in RationalT r)
const pure nothrow if (op == "/") {
return RationalT(num * r.den, den * r.num);
}
RationalT opBinary(string op, U)(in U r)
const pure nothrow if (isIntegral!U && (op == "+" ||
op == "-" || op == "*" || op == "/")) {
return opBinary!op(RationalT(r));
}
RationalT opBinary(string op)(in size_t p)
const pure nothrow if (op == "^^") {
return RationalT(num ^^ p, den ^^ p);
}
RationalT opBinaryRight(string op, U)(in U l)
const pure nothrow if (isIntegral!U) {
return RationalT(l).opBinary!op(RationalT(num, den));
}
RationalT opOpAssign(string op, U)(in U l) pure /*nothrow*/ {
mixin("this = this " ~ op ~ "l;");
return this;
}
RationalT opUnary(string op)()
const pure nothrow if (op == "+" || op == "-") {
return RationalT(mixin(op ~ "num"), den);
}
bool opCast(U)() const if (is(U == bool)) {
return num != 0;
}
bool opEquals(U)(in U r) const pure nothrow {
RationalT rhs = RationalT(r);
if (type() == Type.NaRAT || rhs.type() == Type.NaRAT)
return false;
return num == rhs.num && den == rhs.den;
}
int opCmp(U)(in U r) const pure nothrow {
auto rhs = RationalT(r);
if (type() == Type.NaRAT || rhs.type() == Type.NaRAT)
throw new Error("Compare involve a NaRAT.");
if (type() != Type.NORMAL ||
rhs.type() != Type.NORMAL) // for infinite
return (type() == rhs.type()) ? 0 :
((type() < rhs.type()) ? -1 : 1);
auto diff = num * rhs.den - den * rhs.num;
return (diff == 0) ? 0 : ((diff < 0) ? -1 : 1);
}
Type type() const pure nothrow {
if (den > 0) return Type.NORMAL;
if (den < 0) return Type.NegDEN;
if (num > 0) return Type.PosINF;
if (num < 0) return Type.NegINF;
return Type.NaRAT;
}
}
RationalT!U rational(U)(in U n) pure nothrow {
return typeof(return)(n);
}
RationalT!(CommonType!(U1, U2))
rational(U1, U2)(in U1 n, in U2 d) pure nothrow {
return typeof(return)(n, d);
}
alias Rational = RationalT!BigInt;
version (arithmetic_rational_main) { // Test.
void main() {
import std.stdio, std.math;
alias RatL = RationalT!long;
foreach (immutable p; 2 .. 2 ^^ 19) {
auto sum = RatL(1, p);
immutable limit = 1 + cast(uint)real(p).sqrt;
foreach (immutable factor; 2 .. limit)
if (p % factor == 0)
sum += RatL(1, factor) + RatL(factor, p);
if (sum.denominator == 1)
writefln("Sum of recipr. factors of %6s = %s exactly%s",
p, sum, (sum == 1) ? ", perfect." : ".");
}
}
} |
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geometric mean of two numbers.
The arithmetic-geometric mean of two numbers can be (usefully) denoted as
a
g
m
(
a
,
g
)
{\displaystyle \mathrm {agm} (a,g)}
, and is equal to the limit of the sequence:
a
0
=
a
;
g
0
=
g
{\displaystyle a_{0}=a;\qquad g_{0}=g}
a
n
+
1
=
1
2
(
a
n
+
g
n
)
;
g
n
+
1
=
a
n
g
n
.
{\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.}
Since the limit of
a
n
−
g
n
{\displaystyle a_{n}-g_{n}}
tends (rapidly) to zero with iterations, this is an efficient method.
Demonstrate the function by calculating:
a
g
m
(
1
,
1
/
2
)
{\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})}
Also see
mathworld.wolfram.com/Arithmetic-Geometric Mean
| #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. ARITHMETIC-GEOMETRIC-MEAN-PROG.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 AGM-VARS.
05 A PIC 9V9(16).
05 A-ZERO PIC 9V9(16).
05 G PIC 9V9(16).
05 DIFF PIC 9V9(16) VALUE 1.
* Initialize DIFF with a non-zero value, otherwise AGM-PARAGRAPH
* is never performed at all.
PROCEDURE DIVISION.
TEST-PARAGRAPH.
MOVE 1 TO A.
COMPUTE G = 1 / FUNCTION SQRT(2).
* The program will run with the test values. If you would rather
* calculate the AGM of numbers input at the console, comment out
* TEST-PARAGRAPH and un-comment-out INPUT-A-AND-G-PARAGRAPH.
* INPUT-A-AND-G-PARAGRAPH.
* DISPLAY 'Enter two numbers.'
* ACCEPT A.
* ACCEPT G.
CONTROL-PARAGRAPH.
PERFORM AGM-PARAGRAPH UNTIL DIFF IS LESS THAN 0.000000000000001.
DISPLAY A.
STOP RUN.
AGM-PARAGRAPH.
MOVE A TO A-ZERO.
COMPUTE A = (A-ZERO + G) / 2.
MULTIPLY A-ZERO BY G GIVING G.
COMPUTE G = FUNCTION SQRT(G).
SUBTRACT A FROM G GIVING DIFF.
COMPUTE DIFF = FUNCTION ABS(DIFF). |
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Get two integers from the user, and then (for those two integers), display their:
sum
difference
product
integer quotient
remainder
exponentiation (if the operator exists)
Don't include error handling.
For quotient, indicate how it rounds (e.g. towards zero, towards negative infinity, etc.).
For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
| #VBA | VBA |
'Arithmetic - Integer
Sub RosettaArithmeticInt()
Dim opr As Variant, a As Integer, b As Integer
On Error Resume Next
a = CInt(InputBox("Enter first integer", "XLSM | Arithmetic"))
b = CInt(InputBox("Enter second integer", "XLSM | Arithmetic"))
Debug.Print "a ="; a, "b="; b, vbCr
For Each opr In Split("+ - * / \ mod ^", " ")
Select Case opr
Case "mod": Debug.Print "a mod b", a; "mod"; b, a Mod b
Case "\": Debug.Print "a \ b", a; "\"; b, a \ b
Case Else: Debug.Print "a "; opr; " b", a; opr; b, Evaluate(a & opr & b)
End Select
Next opr
End Sub
|
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #68000_Assembly | 68000 Assembly | *-----------------------------------------------------------
* Title : 100Doors.X68
* Written by : G. A. Tippery
* Date : 2014-01-17
* Description: Solves "100 Doors" problem, see: http://rosettacode.org/wiki/100_doors
* Notes : Translated from C "Unoptimized" version, http://rosettacode.org/wiki/100_doors#unoptimized
* : No optimizations done relative to C version; "for("-equivalent loops could be optimized.
*-----------------------------------------------------------
*
* System-specific general console I/O macros (Sim68K, in this case)
*
PUTS MACRO
** Print a null-terminated string w/o CRLF **
** Usage: PUTS stringaddress
** Returns with D0, A1 modified
MOVEQ #14,D0 ; task number 14 (display null string)
LEA \1,A1 ; address of string
TRAP #15 ; display it
ENDM
*
PRINTN MACRO
** Print decimal integer from number in register
** Usage: PRINTN register
** Returns with D0,D1 modified
IFNC '\1','D1' ;if some register other than D1
MOVE.L \1,D1 ;put number to display in D1
ENDC
MOVE.B #3,D0
TRAP #15 ;display number in D1
*
* Generic constants
*
CR EQU 13 ;ASCII Carriage Return
LF EQU 10 ;ASCII Line Feed
*
* Definitions specific to this program
*
* Register usage:
* D3 == pass (index)
* D4 == door (index)
* A2 == Doors array pointer
*
SIZE EQU 100 ;Define a symbolic constant for # of doors
ORG $1000 ;Specify load address for program -- actual address system-specific
START: ; Execution starts here
LEA Doors,A2 ; make A2 point to Doors byte array
MOVEQ #0,D3
PassLoop:
CMP #SIZE,D3
BCC ExitPassLoop ; Branch on Carry Clear - being used as Branch on Higher or Equal
MOVE D3,D4
DoorLoop:
CMP #SIZE,D4
BCC ExitDoorLoop
NOT.B 0(A2,D4)
ADD D3,D4
ADDQ #1,D4
BRA DoorLoop
ExitDoorLoop:
ADDQ #1,D3
BRA PassLoop
ExitPassLoop:
* $28 = 40. bytes of code to this point. 32626 cycles so far.
* At this point, the result exists as the 100 bytes starting at address Doors.
* To get output, we must use methods specific to the particular hardware, OS, or
* emulator system that the code is running on. I use macros to "hide" some of the
* system-specific details; equivalent macros would be written for another system.
MOVEQ #0,D4
PrintLoop:
CMP #SIZE,D4
BCC ExitPrintLoop
PUTS DoorMsg1
MOVE D4,D1
ADDQ #1,D1 ; Convert index to 1-based instead of 0-based
PRINTN D1
PUTS DoorMsg2
TST.B 0(A2,D4) ; Is this door open (!= 0)?
BNE ItsOpen
PUTS DoorMsgC
BRA Next
ItsOpen:
PUTS DoorMsgO
Next:
ADDQ #1,D4
BRA PrintLoop
ExitPrintLoop:
* What to do at end of program is also system-specific
SIMHALT ;Halt simulator
*
* $78 = 120. bytes of code to this point, but this will depend on how the I/O macros are actually written.
* Cycle count is nearly meaningless, as the I/O hardware and routines will dominate the timing.
*
* Data memory usage
*
ORG $2000
Doors DCB.B SIZE,0 ;Reserve 100 bytes, prefilled with zeros
DoorMsg1 DC.B 'Door ',0
DoorMsg2 DC.B ' is ',0
DoorMsgC DC.B 'closed',CR,LF,0
DoorMsgO DC.B 'open',CR,LF,0
END START ;last line of source
|
http://rosettacode.org/wiki/Arithmetic-geometric_mean/Calculate_Pi | Arithmetic-geometric mean/Calculate Pi | Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate
π
{\displaystyle \pi }
.
With the same notations used in Arithmetic-geometric mean, we can summarize the paper by writing:
π
=
4
a
g
m
(
1
,
1
/
2
)
2
1
−
∑
n
=
1
∞
2
n
+
1
(
a
n
2
−
g
n
2
)
{\displaystyle \pi ={\frac {4\;\mathrm {agm} (1,1/{\sqrt {2}})^{2}}{1-\sum \limits _{n=1}^{\infty }2^{n+1}(a_{n}^{2}-g_{n}^{2})}}}
This allows you to make the approximation, for any large N:
π
≈
4
a
N
2
1
−
∑
k
=
1
N
2
k
+
1
(
a
k
2
−
g
k
2
)
{\displaystyle \pi \approx {\frac {4\;a_{N}^{2}}{1-\sum \limits _{k=1}^{N}2^{k+1}(a_{k}^{2}-g_{k}^{2})}}}
The purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of
π
{\displaystyle \pi }
.
| #R | R | library(Rmpfr)
agm <- function(n, prec) {
s <- mpfr(0, prec)
a <- mpfr(1, prec)
g <- sqrt(mpfr("0.5", prec))
p <- as.bigz(4)
for (i in seq(n)) {
m <- (a + g) / 2L
g <- sqrt(a * g)
a <- m
s <- s + p * (a * a - g * g)
p <- p + p
}
4L * a * a / (1L - s)
}
1e6 * log(10) / log(2)
# [1] 3321928
# Compute pi to one million decimal digits:
p <- 3322000
x <- agm(20, p)
# Check
roundMpfr(x - Const("pi", p), 64)
# 1 'mpfr' number of precision 64 bits
# [1] 4.90382361286485830568e-1000016
# Save to disk
f <- file("pi.txt", "w")
writeLines(formatMpfr(x, 1e6), f)
close(f) |
http://rosettacode.org/wiki/Arithmetic-geometric_mean/Calculate_Pi | Arithmetic-geometric mean/Calculate Pi | Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate
π
{\displaystyle \pi }
.
With the same notations used in Arithmetic-geometric mean, we can summarize the paper by writing:
π
=
4
a
g
m
(
1
,
1
/
2
)
2
1
−
∑
n
=
1
∞
2
n
+
1
(
a
n
2
−
g
n
2
)
{\displaystyle \pi ={\frac {4\;\mathrm {agm} (1,1/{\sqrt {2}})^{2}}{1-\sum \limits _{n=1}^{\infty }2^{n+1}(a_{n}^{2}-g_{n}^{2})}}}
This allows you to make the approximation, for any large N:
π
≈
4
a
N
2
1
−
∑
k
=
1
N
2
k
+
1
(
a
k
2
−
g
k
2
)
{\displaystyle \pi \approx {\frac {4\;a_{N}^{2}}{1-\sum \limits _{k=1}^{N}2^{k+1}(a_{k}^{2}-g_{k}^{2})}}}
The purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of
π
{\displaystyle \pi }
.
| #Racket | Racket | #lang racket
(require math/bigfloat)
(define (pi/a-g rep)
(let loop ([a 1.bf]
[g (bf1/sqrt 2.bf)]
[z (bf/ 1.bf 4.bf)]
[n (bf 1)]
[r 0])
(if (< r rep)
(let* ([a-p (bf/ (bf+ a g) 2.bf)]
[g-p (bfsqrt (bf* a g))]
[z-p (bf- z (bf* (bfsqr (bf- a-p a)) n))])
(loop a-p g-p z-p (bf* n 2.bf) (add1 r)))
(bf/ (bfsqr a) z))))
(parameterize ([bf-precision 100])
(displayln (bigfloat->string (pi/a-g 5)))
(displayln (bigfloat->string pi.bf)))
(parameterize ([bf-precision 200])
(displayln (bigfloat->string (pi/a-g 6)))
(displayln (bigfloat->string pi.bf))) |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #Avail | Avail | tup ::= <"aardvark", "cat", "dog">; |
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part", where the imaginary part is the number to be multiplied by
i
{\displaystyle i}
.
Task
Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.)
Print the results for each operation tested.
Optional: Show complex conjugation.
By definition, the complex conjugate of
a
+
b
i
{\displaystyle a+bi}
is
a
−
b
i
{\displaystyle a-bi}
Some languages have complex number libraries available. If your language does, show the operations. If your language does not, also show the definition of this type.
| #CoffeeScript | CoffeeScript |
# create an immutable Complex type
class Complex
constructor: (@r=0, @i=0) ->
@magnitude = @r*@r + @i*@i
plus: (c2) ->
new Complex(
@r + c2.r,
@i + c2.i
)
times: (c2) ->
new Complex(
@r*c2.r - @i*c2.i,
@r*c2.i + @i*c2.r
)
negation: ->
new Complex(
-1 * @r,
-1 * @i
)
inverse: ->
throw Error "no inverse" if @magnitude is 0
new Complex(
@r / @magnitude,
-1 * @i / @magnitude
)
toString: ->
return "#{@r}" if @i == 0
return "#{@i}i" if @r == 0
if @i > 0
"#{@r} + #{@i}i"
else
"#{@r} - #{-1 * @i}i"
# test
do ->
a = new Complex(5, 3)
b = new Complex(4, -3)
sum = a.plus b
console.log "(#{a}) + (#{b}) = #{sum}"
product = a.times b
console.log "(#{a}) * (#{b}) = #{product}"
negation = b.negation()
console.log "-1 * (#{b}) = #{negation}"
diff = a.plus negation
console.log "(#{a}) - (#{b}) = #{diff}"
inverse = b.inverse()
console.log "1 / (#{b}) = #{inverse}"
quotient = product.times inverse
console.log "(#{product}) / (#{b}) = #{quotient}"
|
http://rosettacode.org/wiki/Arena_storage_pool | Arena storage pool | Dynamically allocated objects take their memory from a heap.
The memory for an object is provided by an allocator which maintains the storage pool used for the heap.
Often a call to allocator is denoted as
P := new T
where T is the type of an allocated object, and P is a reference to the object.
The storage pool chosen by the allocator can be determined by either:
the object type T
the type of pointer P
In the former case objects can be allocated only in one storage pool.
In the latter case objects of the type can be allocated in any storage pool or on the stack.
Task
The task is to show how allocators and user-defined storage pools are supported by the language.
In particular:
define an arena storage pool. An arena is a pool in which objects are allocated individually, but freed by groups.
allocate some objects (e.g., integers) in the pool.
Explain what controls the storage pool choice in the language.
| #Rust | Rust | #![feature(rustc_private)]
extern crate arena;
use arena::TypedArena;
fn main() {
// Memory is allocated using the default allocator (currently jemalloc). The memory is
// allocated in chunks, and when one chunk is full another is allocated. This ensures that
// references to an arena don't become invalid when the original chunk runs out of space. The
// chunk size is configurable as an argument to TypedArena::with_capacity if necessary.
let arena = TypedArena::new();
// The arena crate contains two types of arenas: TypedArena and Arena. Arena is
// reflection-basd and slower, but can allocate objects of any type. TypedArena is faster, and
// can allocate only objects of one type. The type is determined by type inference--if you try
// to allocate an integer, then Rust's compiler knows it is an integer arena.
let v1 = arena.alloc(1i32);
// TypedArena returns a mutable reference
let v2 = arena.alloc(3);
*v2 += 38;
println!("{}", *v1 + *v2);
// The arena's destructor is called as it goes out of scope, at which point it deallocates
// everything stored within it at once.
} |
http://rosettacode.org/wiki/Arena_storage_pool | Arena storage pool | Dynamically allocated objects take their memory from a heap.
The memory for an object is provided by an allocator which maintains the storage pool used for the heap.
Often a call to allocator is denoted as
P := new T
where T is the type of an allocated object, and P is a reference to the object.
The storage pool chosen by the allocator can be determined by either:
the object type T
the type of pointer P
In the former case objects can be allocated only in one storage pool.
In the latter case objects of the type can be allocated in any storage pool or on the stack.
Task
The task is to show how allocators and user-defined storage pools are supported by the language.
In particular:
define an arena storage pool. An arena is a pool in which objects are allocated individually, but freed by groups.
allocate some objects (e.g., integers) in the pool.
Explain what controls the storage pool choice in the language.
| #Scala | Scala | package require Tcl 8.6
oo::class create Pool {
superclass oo::class
variable capacity pool busy
unexport create
constructor args {
next {*}$args
set capacity 100
set pool [set busy {}]
}
method new {args} {
if {[llength $pool]} {
set pool [lassign $pool obj]
} else {
if {[llength $busy] >= $capacity} {
throw {POOL CAPACITY} "exceeded capacity: $capacity"
}
set obj [next]
set newobj [namespace current]::[namespace tail $obj]
rename $obj $newobj
set obj $newobj
}
try {
[info object namespace $obj]::my Init {*}$args
} on error {msg opt} {
lappend pool $obj
return -options $opt $msg
}
lappend busy $obj
return $obj
}
method ReturnToPool obj {
try {
if {"Finalize" in [info object methods $obj -all -private]} {
[info object namespace $obj]::my Finalize
}
} on error {msg opt} {
after 0 [list return -options $opt $msg]
return false
}
set idx [lsearch -exact $busy $obj]
set busy [lreplace $busy $idx $idx]
if {[llength $pool] + [llength $busy] + 1 <= $capacity} {
lappend pool $obj
return true
} else {
return false
}
}
method capacity {{value {}}} {
if {[llength [info level 0]] == 3} {
if {$value < $capacity} {
while {[llength $pool] > 0 && [llength $pool] + [llength $busy] > $value} {
set pool [lassign $pool obj]
rename $obj {}
}
}
set capacity [expr {$value >> 0}]
} else {
return $capacity
}
}
method clearPool {} {
foreach obj $busy {
$obj destroy
}
}
method destroy {} {
my clearPool
next
}
self method create {class {definition {}}} {
set cls [next $class $definition]
oo::define $cls method destroy {} {
if {![[info object namespace [self class]]::my ReturnToPool [self]]} {
next
}
}
return $cls
}
} |
http://rosettacode.org/wiki/Arithmetic/Rational | Arithmetic/Rational | Task
Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language.
Example
Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number).
Further define the appropriate rational unary operators abs and '-', with the binary operators for addition '+', subtraction '-', multiplication '×', division '/', integer division '÷', modulo division, the comparison operators (e.g. '<', '≤', '>', & '≥') and equality operators (e.g. '=' & '≠').
Define standard coercion operators for casting int to frac etc.
If space allows, define standard increment and decrement operators (e.g. '+:=' & '-:=' etc.).
Finally test the operators:
Use the new type frac to find all perfect numbers less than 219 by summing the reciprocal of the factors.
Related task
Perfect Numbers
| #Delphi | Delphi |
program Arithmetic_Rational;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
Boost.Rational;
var
sum: TFraction;
max: Integer = 1 shl 19;
candidate, max2, factor: Integer;
begin
for candidate := 2 to max - 1 do
begin
sum := Fraction(1, candidate);
max2 := Trunc(Sqrt(candidate));
for factor := 2 to max2 do
begin
if (candidate mod factor) = 0 then
begin
sum := sum + Fraction(1, factor);
sum := sum + Fraction(1, candidate div factor);
end;
end;
if sum = Fraction(1) then
Writeln(candidate, ' is perfect');
end;
Readln;
end. |
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geometric mean of two numbers.
The arithmetic-geometric mean of two numbers can be (usefully) denoted as
a
g
m
(
a
,
g
)
{\displaystyle \mathrm {agm} (a,g)}
, and is equal to the limit of the sequence:
a
0
=
a
;
g
0
=
g
{\displaystyle a_{0}=a;\qquad g_{0}=g}
a
n
+
1
=
1
2
(
a
n
+
g
n
)
;
g
n
+
1
=
a
n
g
n
.
{\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.}
Since the limit of
a
n
−
g
n
{\displaystyle a_{n}-g_{n}}
tends (rapidly) to zero with iterations, this is an efficient method.
Demonstrate the function by calculating:
a
g
m
(
1
,
1
/
2
)
{\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})}
Also see
mathworld.wolfram.com/Arithmetic-Geometric Mean
| #Common_Lisp | Common Lisp | (defun agm (a0 g0 &optional (tolerance 1d-8))
(loop for a = a0 then (* (+ a g) 5d-1)
and g = g0 then (sqrt (* a g))
until (< (abs (- a g)) tolerance)
finally (return a)))
|
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geometric mean of two numbers.
The arithmetic-geometric mean of two numbers can be (usefully) denoted as
a
g
m
(
a
,
g
)
{\displaystyle \mathrm {agm} (a,g)}
, and is equal to the limit of the sequence:
a
0
=
a
;
g
0
=
g
{\displaystyle a_{0}=a;\qquad g_{0}=g}
a
n
+
1
=
1
2
(
a
n
+
g
n
)
;
g
n
+
1
=
a
n
g
n
.
{\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.}
Since the limit of
a
n
−
g
n
{\displaystyle a_{n}-g_{n}}
tends (rapidly) to zero with iterations, this is an efficient method.
Demonstrate the function by calculating:
a
g
m
(
1
,
1
/
2
)
{\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})}
Also see
mathworld.wolfram.com/Arithmetic-Geometric Mean
| #D | D | import std.stdio, std.math, std.meta, std.typecons;
real agm(real a, real g, in int bitPrecision=60) pure nothrow @nogc @safe {
do {
//{a, g} = {(a + g) / 2.0, sqrt(a * g)};
AliasSeq!(a, g) = tuple((a + g) / 2.0, sqrt(a * g));
} while (feqrel(a, g) < bitPrecision);
return a;
}
void main() @safe {
writefln("%0.19f", agm(1, 1 / sqrt(2.0)));
} |
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Get two integers from the user, and then (for those two integers), display their:
sum
difference
product
integer quotient
remainder
exponentiation (if the operator exists)
Don't include error handling.
For quotient, indicate how it rounds (e.g. towards zero, towards negative infinity, etc.).
For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
| #VBScript | VBScript | option explicit
dim a, b
wscript.stdout.write "A? "
a = wscript.stdin.readline
wscript.stdout.write "B? "
b = wscript.stdin.readline
a = int( a )
b = int( b )
wscript.echo "a + b=", a + b
wscript.echo "a - b=", a - b
wscript.echo "a * b=", a * b
wscript.echo "a / b=", a / b
wscript.echo "a \ b=", a \ b
wscript.echo "a mod b=", a mod b
wscript.echo "a ^ b=", a ^ b |
http://rosettacode.org/wiki/Arithmetic_evaluation | Arithmetic evaluation | Create a program which parses and evaluates arithmetic expressions.
Requirements
An abstract-syntax tree (AST) for the expression must be created from parsing the input.
The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.)
The expression will be a string or list of symbols like "(1+3)*7".
The four symbols + - * / must be supported as binary operators with conventional precedence rules.
Precedence-control parentheses must also be supported.
Note
For those who don't remember, mathematical precedence is as follows:
Parentheses
Multiplication/Division (left to right)
Addition/Subtraction (left to right)
C.f
24 game Player.
Parsing/RPN calculator algorithm.
Parsing/RPN to infix conversion.
| #11l | 11l | T Symbol
String id
Int lbp
Int nud_bp
Int led_bp
(ASTNode -> ASTNode) nud
((ASTNode, ASTNode) -> ASTNode) led
F set_nud_bp(nud_bp, nud)
.nud_bp = nud_bp
.nud = nud
F set_led_bp(led_bp, led)
.led_bp = led_bp
.led = led
T ASTNode
Symbol& symbol
Int value
ASTNode? first_child
ASTNode? second_child
F eval()
S .symbol.id
‘(number)’
R .value
‘+’
R .first_child.eval() + .second_child.eval()
‘-’
R I .second_child == N {-.first_child.eval()} E .first_child.eval() - .second_child.eval()
‘*’
R .first_child.eval() * .second_child.eval()
‘/’
R .first_child.eval() / .second_child.eval()
‘(’
R .first_child.eval()
E
assert(0B)
R 0
[String = Symbol] symbol_table
[String] tokens
V tokeni = -1
ASTNode token_node
F advance(sid = ‘’)
I sid != ‘’
assert(:token_node.symbol.id == sid)
:tokeni++
:token_node = ASTNode()
I :tokeni == :tokens.len
:token_node.symbol = :symbol_table[‘(end)’]
R
V token = :tokens[:tokeni]
:token_node.symbol = :symbol_table[I token.is_digit() {‘(number)’} E token]
I token.is_digit()
:token_node.value = Int(token)
F expression(rbp = 0)
ASTNode t = move(:token_node)
advance()
V left = t.symbol.nud(move(t))
L rbp < :token_node.symbol.lbp
t = move(:token_node)
advance()
left = t.symbol.led(t, move(left))
R left
F parse(expr_str) -> ASTNode
:tokens = re:‘\s*(\d+|.)’.find_strings(expr_str)
:tokeni = -1
advance()
R expression()
F symbol(id, bp = 0) -> &
I !(id C :symbol_table)
V s = Symbol()
s.id = id
s.lbp = bp
:symbol_table[id] = s
R :symbol_table[id]
F infix(id, bp)
F led(ASTNode self, ASTNode left)
self.first_child = left
self.second_child = expression(self.symbol.led_bp)
R self
symbol(id, bp).set_led_bp(bp, led)
F prefix(id, bp)
F nud(ASTNode self)
self.first_child = expression(self.symbol.nud_bp)
R self
symbol(id).set_nud_bp(bp, nud)
infix(‘+’, 1)
infix(‘-’, 1)
infix(‘*’, 2)
infix(‘/’, 2)
prefix(‘-’, 3)
F nud(ASTNode self)
R self
symbol(‘(number)’).nud = nud
symbol(‘(end)’)
F nud_parens(ASTNode self)
V expr = expression()
advance(‘)’)
R expr
symbol(‘(’).nud = nud_parens
symbol(‘)’)
L(expr_str) [‘-2 / 2 + 4 + 3 * 2’,
‘2 * (3 + (4 * 5 + (6 * 7) * 8) - 9) * 10’]
print(expr_str‘ = ’parse(expr_str).eval()) |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #8080_Assembly | 8080 Assembly | page: equ 2 ; Store doors in page 2
doors: equ 100 ; 100 doors
puts: equ 9 ; CP/M string output
org 100h
xra a ; Set all doors to zero
lxi h,256*page
mvi c,doors
zero: mov m,a
inx h
dcr c
jnz zero
mvi m,'$' ; CP/M string terminator (for easier output later)
mov d,a ; D=0 so that DE=E=pass counter
mov e,a ; E=0, first pass
mvi a,doors-1 ; Last pass and door
pass: mov l,e ; L=door counter, start at first door in pass
door: inr m ; Incrementing always toggles the low bit
dad d ; Go to next door in pass
inr l
cmp l ; Was this the last door?
jnc door ; If not, do the next door
inr e ; Next pass
cmp e ; Was this the last pass?
jnc pass ; If not, do the next pass
lxi h,256*page
mvi c,doors ; Door counter
lxi d,130h ; D=1 (low bit), E=30h (ascii 0)
char: mov a,m ; Get door
ana d ; Low bit gives door status
ora e ; ASCII 0 or 1
mov m,a ; Write character back
inx h ; Next door
dcr c ; Any doors left?
jnz char ; If so, next door
lxi d,256*page
mvi c,puts ; CP/M system call to print the string
jmp 5 |
http://rosettacode.org/wiki/Arithmetic-geometric_mean/Calculate_Pi | Arithmetic-geometric mean/Calculate Pi | Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate
π
{\displaystyle \pi }
.
With the same notations used in Arithmetic-geometric mean, we can summarize the paper by writing:
π
=
4
a
g
m
(
1
,
1
/
2
)
2
1
−
∑
n
=
1
∞
2
n
+
1
(
a
n
2
−
g
n
2
)
{\displaystyle \pi ={\frac {4\;\mathrm {agm} (1,1/{\sqrt {2}})^{2}}{1-\sum \limits _{n=1}^{\infty }2^{n+1}(a_{n}^{2}-g_{n}^{2})}}}
This allows you to make the approximation, for any large N:
π
≈
4
a
N
2
1
−
∑
k
=
1
N
2
k
+
1
(
a
k
2
−
g
k
2
)
{\displaystyle \pi \approx {\frac {4\;a_{N}^{2}}{1-\sum \limits _{k=1}^{N}2^{k+1}(a_{k}^{2}-g_{k}^{2})}}}
The purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of
π
{\displaystyle \pi }
.
| #Raku | Raku | constant number-of-decimals = 100;
multi sqrt(Int $n) {
my $guess = 10**($n.chars div 2);
my $iterator = { ( $^x + $n div ($^x) ) div 2 };
my $endpoint = { $^x == $^y|$^z };
return min (+$guess, $iterator … $endpoint)[*-1, *-2];
}
multi sqrt(FatRat $r --> FatRat) {
return FatRat.new:
sqrt($r.nude[0] * 10**(number-of-decimals*2) div $r.nude[1]),
10**number-of-decimals;
}
my FatRat ($a, $n) = 1.FatRat xx 2;
my FatRat $g = sqrt(1/2.FatRat);
my $z = .25;
for ^10 {
given [ ($a + $g)/2, sqrt($a * $g) ] {
$z -= (.[0] - $a)**2 * $n;
$n += $n;
($a, $g) = @$_;
say ($a ** 2 / $z).substr: 0, 2 + number-of-decimals;
}
} |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #AWK | AWK | BEGIN {
# to make an array, assign elements to it
array[1] = "first"
array[2] = "second"
array[3] = "third"
alen = 3 # want the length? store in separate variable
# or split a string
plen = split("2 3 5 7 11 13 17 19 23 29", primes)
clen = split("Ottawa;Washington DC;Mexico City", cities, ";")
# retrieve an element
print "The 6th prime number is " primes[6]
# push an element
cities[clen += 1] = "New York"
dump("An array", array, alen)
dump("Some primes", primes, plen)
dump("A list of cities", cities, clen)
}
function dump(what, array, len, i) {
print what;
# iterate an array in order
for (i = 1; i <= len; i++) {
print " " i ": " array[i]
}
} |
http://rosettacode.org/wiki/Arithmetic/Complex | Arithmetic/Complex | A complex number is a number which can be written as:
a
+
b
×
i
{\displaystyle a+b\times i}
(sometimes shown as:
b
+
a
×
i
{\displaystyle b+a\times i}
where
a
{\displaystyle a}
and
b
{\displaystyle b}
are real numbers, and
i
{\displaystyle i}
is √ -1
Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part", where the imaginary part is the number to be multiplied by
i
{\displaystyle i}
.
Task
Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.)
Print the results for each operation tested.
Optional: Show complex conjugation.
By definition, the complex conjugate of
a
+
b
i
{\displaystyle a+bi}
is
a
−
b
i
{\displaystyle a-bi}
Some languages have complex number libraries available. If your language does, show the operations. If your language does not, also show the definition of this type.
| #Common_Lisp | Common Lisp | > (sqrt -1)
#C(0.0 1.0)
> (expt #c(0 1) 2)
-1 |
http://rosettacode.org/wiki/Arena_storage_pool | Arena storage pool | Dynamically allocated objects take their memory from a heap.
The memory for an object is provided by an allocator which maintains the storage pool used for the heap.
Often a call to allocator is denoted as
P := new T
where T is the type of an allocated object, and P is a reference to the object.
The storage pool chosen by the allocator can be determined by either:
the object type T
the type of pointer P
In the former case objects can be allocated only in one storage pool.
In the latter case objects of the type can be allocated in any storage pool or on the stack.
Task
The task is to show how allocators and user-defined storage pools are supported by the language.
In particular:
define an arena storage pool. An arena is a pool in which objects are allocated individually, but freed by groups.
allocate some objects (e.g., integers) in the pool.
Explain what controls the storage pool choice in the language.
| #Tcl | Tcl | package require Tcl 8.6
oo::class create Pool {
superclass oo::class
variable capacity pool busy
unexport create
constructor args {
next {*}$args
set capacity 100
set pool [set busy {}]
}
method new {args} {
if {[llength $pool]} {
set pool [lassign $pool obj]
} else {
if {[llength $busy] >= $capacity} {
throw {POOL CAPACITY} "exceeded capacity: $capacity"
}
set obj [next]
set newobj [namespace current]::[namespace tail $obj]
rename $obj $newobj
set obj $newobj
}
try {
[info object namespace $obj]::my Init {*}$args
} on error {msg opt} {
lappend pool $obj
return -options $opt $msg
}
lappend busy $obj
return $obj
}
method ReturnToPool obj {
try {
if {"Finalize" in [info object methods $obj -all -private]} {
[info object namespace $obj]::my Finalize
}
} on error {msg opt} {
after 0 [list return -options $opt $msg]
return false
}
set idx [lsearch -exact $busy $obj]
set busy [lreplace $busy $idx $idx]
if {[llength $pool] + [llength $busy] + 1 <= $capacity} {
lappend pool $obj
return true
} else {
return false
}
}
method capacity {{value {}}} {
if {[llength [info level 0]] == 3} {
if {$value < $capacity} {
while {[llength $pool] > 0 && [llength $pool] + [llength $busy] > $value} {
set pool [lassign $pool obj]
rename $obj {}
}
}
set capacity [expr {$value >> 0}]
} else {
return $capacity
}
}
method clearPool {} {
foreach obj $busy {
$obj destroy
}
}
method destroy {} {
my clearPool
next
}
self method create {class {definition {}}} {
set cls [next $class $definition]
oo::define $cls method destroy {} {
if {![[info object namespace [self class]]::my ReturnToPool [self]]} {
next
}
}
return $cls
}
} |
http://rosettacode.org/wiki/Arithmetic/Rational | Arithmetic/Rational | Task
Create a reasonably complete implementation of rational arithmetic in the particular language using the idioms of the language.
Example
Define a new type called frac with binary operator "//" of two integers that returns a structure made up of the numerator and the denominator (as per a rational number).
Further define the appropriate rational unary operators abs and '-', with the binary operators for addition '+', subtraction '-', multiplication '×', division '/', integer division '÷', modulo division, the comparison operators (e.g. '<', '≤', '>', & '≥') and equality operators (e.g. '=' & '≠').
Define standard coercion operators for casting int to frac etc.
If space allows, define standard increment and decrement operators (e.g. '+:=' & '-:=' etc.).
Finally test the operators:
Use the new type frac to find all perfect numbers less than 219 by summing the reciprocal of the factors.
Related task
Perfect Numbers
| #EchoLisp | EchoLisp |
;; Finding perfect numbers
(define (sum/inv n) ;; look for div's in [2..sqrt(n)] and add 1/n
(for/fold (acc (/ n)) [(i (in-range 2 (sqrt n)))]
#:break (> acc 1) ; no hope
(when (zero? (modulo n i ))
(set! acc (+ acc (/ i) (/ i n))))))
|
http://rosettacode.org/wiki/Arithmetic-geometric_mean | Arithmetic-geometric mean |
This page uses content from Wikipedia. The original article was at Arithmetic-geometric mean. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Write a function to compute the arithmetic-geometric mean of two numbers.
The arithmetic-geometric mean of two numbers can be (usefully) denoted as
a
g
m
(
a
,
g
)
{\displaystyle \mathrm {agm} (a,g)}
, and is equal to the limit of the sequence:
a
0
=
a
;
g
0
=
g
{\displaystyle a_{0}=a;\qquad g_{0}=g}
a
n
+
1
=
1
2
(
a
n
+
g
n
)
;
g
n
+
1
=
a
n
g
n
.
{\displaystyle a_{n+1}={\tfrac {1}{2}}(a_{n}+g_{n});\quad g_{n+1}={\sqrt {a_{n}g_{n}}}.}
Since the limit of
a
n
−
g
n
{\displaystyle a_{n}-g_{n}}
tends (rapidly) to zero with iterations, this is an efficient method.
Demonstrate the function by calculating:
a
g
m
(
1
,
1
/
2
)
{\displaystyle \mathrm {agm} (1,1/{\sqrt {2}})}
Also see
mathworld.wolfram.com/Arithmetic-Geometric Mean
| #Delphi | Delphi |
program geometric_mean;
{$APPTYPE CONSOLE}
uses
System.SysUtils;
function Fabs(value: Double): Double;
begin
Result := value;
if Result < 0 then
Result := -Result;
end;
function agm(a, g: Double):Double;
var
iota, a1, g1: Double;
begin
iota := 1.0E-16;
if a * g < 0.0 then
begin
Writeln('arithmetic-geometric mean undefined when x*y<0');
exit(1);
end;
while Fabs(a - g) > iota do
begin
a1 := (a + g) / 2.0;
g1 := sqrt(a * g);
a := a1;
g := g1;
end;
Exit(a);
end;
var
x, y: Double;
begin
Write('Enter two numbers:');
Readln(x, y);
writeln(format('The arithmetic-geometric mean is %.6f', [agm(x, y)]));
readln;
end. |
http://rosettacode.org/wiki/Arithmetic/Integer | Arithmetic/Integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Get two integers from the user, and then (for those two integers), display their:
sum
difference
product
integer quotient
remainder
exponentiation (if the operator exists)
Don't include error handling.
For quotient, indicate how it rounds (e.g. towards zero, towards negative infinity, etc.).
For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different.
| #Vedit_macro_language | Vedit macro language | #1 = Get_Num("Give number a: ")
#2 = Get_Num("Give number b: ")
Message("a + b = ") Num_Type(#1 + #2)
Message("a - b = ") Num_Type(#1 - #2)
Message("a * b = ") Num_Type(#1 * #2)
Message("a / b = ") Num_Type(#1 / #2)
Message("a % b = ") Num_Type(#1 % #2) |
http://rosettacode.org/wiki/Arithmetic_evaluation | Arithmetic evaluation | Create a program which parses and evaluates arithmetic expressions.
Requirements
An abstract-syntax tree (AST) for the expression must be created from parsing the input.
The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.)
The expression will be a string or list of symbols like "(1+3)*7".
The four symbols + - * / must be supported as binary operators with conventional precedence rules.
Precedence-control parentheses must also be supported.
Note
For those who don't remember, mathematical precedence is as follows:
Parentheses
Multiplication/Division (left to right)
Addition/Subtraction (left to right)
C.f
24 game Player.
Parsing/RPN calculator algorithm.
Parsing/RPN to infix conversion.
| #Ada | Ada | INT base=10;
MODE FIXED = LONG REAL; # numbers in the format 9,999.999 #
#IF build abstract syntax tree and then EVAL tree #
MODE AST = UNION(NODE, FIXED);
MODE NUM = REF AST;
MODE NODE = STRUCT(NUM a, PROC (FIXED,FIXED)FIXED op, NUM b);
OP EVAL = (NUM ast)FIXED:(
CASE ast IN
(FIXED num): num,
(NODE fork): (op OF fork)(EVAL( a OF fork), EVAL (b OF fork))
ESAC
);
OP + = (NUM a,b)NUM: ( HEAP AST := NODE(a, (FIXED a,b)FIXED:a+b, b) );
OP - = (NUM a,b)NUM: ( HEAP AST := NODE(a, (FIXED a,b)FIXED:a-b, b) );
OP * = (NUM a,b)NUM: ( HEAP AST := NODE(a, (FIXED a,b)FIXED:a*b, b) );
OP / = (NUM a,b)NUM: ( HEAP AST := NODE(a, (FIXED a,b)FIXED:a/b, b) );
OP **= (NUM a,b)NUM: ( HEAP AST := NODE(a, (FIXED a,b)FIXED:a**b, b) );
#ELSE simply use REAL arithmetic with no abstract syntax tree at all # CO
MODE NUM = FIXED, AST = FIXED;
OP EVAL = (FIXED num)FIXED: num;
#FI# END CO
MODE LEX = PROC (TOK)NUM;
MODE MONADIC =PROC (NUM)NUM;
MODE DIADIC = PROC (NUM,NUM)NUM;
MODE TOK = CHAR;
MODE ACTION = UNION(STACKACTION, LEX, MONADIC, DIADIC);
MODE OPVAL = STRUCT(INT prio, ACTION action);
MODE OPITEM = STRUCT(TOK token, OPVAL opval);
[256]STACKITEM stack;
MODE STACKITEM = STRUCT(NUM value, OPVAL op);
MODE STACKACTION = PROC (REF STACKITEM)VOID;
PROC begin = (REF STACKITEM top)VOID: prio OF op OF top -:= +10;
PROC end = (REF STACKITEM top)VOID: prio OF op OF top -:= -10;
OP ** = (COMPL a,b)COMPL: complex exp(complex ln(a)*b);
[8]OPITEM op list :=(
# OP PRIO ACTION #
("^", (8, (NUM a,b)NUM: a**b)),
("*", (7, (NUM a,b)NUM: a*b)),
("/", (7, (NUM a,b)NUM: a/b)),
("+", (6, (NUM a,b)NUM: a+b)),
("-", (6, (NUM a,b)NUM: a-b)),
("(",(+10, begin)),
(")",(-10, end)),
("?", (9, LEX:SKIP))
);
PROC op dict = (TOK op)REF OPVAL:(
# This can be unrolled to increase performance #
REF OPITEM candidate;
FOR i TO UPB op list WHILE
candidate := op list[i];
# WHILE # op /= token OF candidate DO
SKIP
OD;
opval OF candidate
);
PROC build ast = (STRING expr)NUM:(
INT top:=0;
PROC compress ast stack = (INT prio, NUM in value)NUM:(
NUM out value := in value;
FOR loc FROM top BY -1 TO 1 WHILE
REF STACKITEM stack top := stack[loc];
# WHILE # ( top >= LWB stack | prio <= prio OF op OF stack top | FALSE ) DO
top := loc - 1;
out value :=
CASE action OF op OF stack top IN
(MONADIC op): op(value OF stack top), # not implemented #
(DIADIC op): op(value OF stack top,out value)
ESAC
OD;
out value
);
NUM value := NIL;
FIXED num value;
INT decimal places;
FOR i TO UPB expr DO
TOK token = expr[i];
REF OPVAL this op := op dict(token);
CASE action OF this op IN
(STACKACTION action):(
IF prio OF thisop = -10 THEN
value := compress ast stack(0, value)
FI;
IF top >= LWB stack THEN
action(stack[top])
FI
),
(LEX):( # a crude lexer #
SHORT INT digit = ABS token - ABS "0";
IF 0<= digit AND digit < base THEN
IF NUM(value) IS NIL THEN # first digit #
decimal places := 0;
value := HEAP AST := num value := digit
ELSE
NUM(value) := num value := IF decimal places = 0
THEN
num value * base + digit
ELSE
decimal places *:= base;
num value + digit / decimal places
FI
FI
ELIF token = "." THEN
decimal places := 1
ELSE
SKIP # and ignore spaces and any unrecognised characters #
FI
),
(MONADIC): SKIP, # not implemented #
(DIADIC):(
value := compress ast stack(prio OF this op, value);
IF top=UPB stack THEN index error FI;
stack[top+:=1]:=STACKITEM(value, this op);
value:=NIL
)
ESAC
OD;
compress ast stack(-max int, value)
);
test:(
printf(($" euler's number is about: "g(-long real width,long real width-2)l$,
EVAL build ast("1+1+(1+(1+(1+(1+(1+(1+(1+(1+(1+(1+(1+(1+(1+1/15)/14)/13)/12)/11)/10)/9)/8)/7)/6)/5)/4)/3)/2")));
SKIP EXIT
index error:
printf(("Stack over flow"))
) |
http://rosettacode.org/wiki/100_doors | 100 doors | There are 100 doors in a row that are all initially closed.
You make 100 passes by the doors.
The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it).
The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it.
The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.
Task
Answer the question: what state are the doors in after the last pass? Which are open, which are closed?
Alternate:
As noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.
Opening only those doors is an optimization that may also be expressed;
however, as should be obvious, this defeats the intent of comparing implementations across programming languages.
| #8086_Assembly | 8086 Assembly |
\ Array of doors; init to empty; accessing a non-extant member will return
\ 'null', which is treated as 'false', so we don't need to initialize it:
[] var, doors
\ given a door number, get the value and toggle it:
: toggle-door \ n --
doors @ over a:@
not rot swap a:! drop ;
\ print which doors are open:
: .doors
(
doors @ over a:@ nip
if . space else drop then
) 1 100 loop ;
\ iterate over the doors, skipping 'n':
: main-pass \ n --
0
true
repeat
drop
dup toggle-door
over n:+
dup 101 <
while 2drop drop ;
\ calculate the first 100 doors:
' main-pass 1 100 loop
\ print the results:
.doors cr bye
|
http://rosettacode.org/wiki/Arithmetic-geometric_mean/Calculate_Pi | Arithmetic-geometric mean/Calculate Pi | Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate
π
{\displaystyle \pi }
.
With the same notations used in Arithmetic-geometric mean, we can summarize the paper by writing:
π
=
4
a
g
m
(
1
,
1
/
2
)
2
1
−
∑
n
=
1
∞
2
n
+
1
(
a
n
2
−
g
n
2
)
{\displaystyle \pi ={\frac {4\;\mathrm {agm} (1,1/{\sqrt {2}})^{2}}{1-\sum \limits _{n=1}^{\infty }2^{n+1}(a_{n}^{2}-g_{n}^{2})}}}
This allows you to make the approximation, for any large N:
π
≈
4
a
N
2
1
−
∑
k
=
1
N
2
k
+
1
(
a
k
2
−
g
k
2
)
{\displaystyle \pi \approx {\frac {4\;a_{N}^{2}}{1-\sum \limits _{k=1}^{N}2^{k+1}(a_{k}^{2}-g_{k}^{2})}}}
The purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of
π
{\displaystyle \pi }
.
| #REXX | REXX | /*REXX program calculates the value of pi using the AGM algorithm. */
parse arg d .; if d=='' | d=="," then d= 500 /*D not specified? Then use default. */
numeric digits d+5 /*set the numeric decimal digits to D+5*/
z= 1/4; a= 1; g= sqrt(1/2) /*calculate some initial values. */
n= 1
do j=1 until a==old; old= a /*keep calculating until no more noise.*/
x= (a+g) * .5; g= sqrt(a*g) /*calculate the next set of terms. */
z= z - n*(x-a)**2; n= n+n; a= x /*Z is used in the final calculation. */
end /*j*/ /* [↑] stop if A equals OLD. */
pi= a**2 / z /*compute the finished value of pi. */
numeric digits d /*set the numeric decimal digits to D.*/
say pi / 1 /*display the computed value of pi. */
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); numeric digits; h=d+6
numeric form; m.=9; parse value format(x,2,1,,0) 'E0' with g "E" _ .; g=g *.5'e'_ %2
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*/
numeric digits d; return g/1 |
http://rosettacode.org/wiki/Arrays | Arrays | This task is about arrays.
For hashes or associative arrays, please see Creating an Associative Array.
For a definition and in-depth discussion of what an array is, see Array.
Task
Show basic array syntax in your language.
Basically, create an array, assign a value to it, and retrieve an element (if available, show both fixed-length arrays and
dynamic arrays, pushing a value into it).
Please discuss at Village Pump: Arrays.
Please merge code in from these obsolete tasks:
Creating an Array
Assigning Values to an Array
Retrieving an Element of an Array
Related tasks
Collections
Creating an Associative Array
Two-dimensional array (runtime)
| #Axe | Axe | 1→{L₁}
2→{L₁+1}
3→{L₁+2}
4→{L₁+3}
Disp {L₁}►Dec,i
Disp {L₁+1}►Dec,i
Disp {L₁+2}►Dec,i
Disp {L₁+3}►Dec,i |