Initial data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 72d218235f
commit f23f22d71c
199087 changed files with 3378941 additions and 0 deletions

View file

@ -0,0 +1,2 @@
---
from: http://rosettacode.org/wiki/Van_der_Corput_sequence

View file

@ -0,0 +1,56 @@
When counting integers in binary, if you put a (binary) point to the right of the count then the column immediately to the left denotes a digit with a multiplier of <math>2^0</math>; the digit in the next column to the left has a multiplier of <math>2^1</math>; and so on.
So in the following table:
<pre> 0.
1.
10.
11.
...</pre>
the binary number "<code>10</code>" is <math>1 \times 2^1 + 0 \times 2^0</math>.
You can also have binary digits to the right of the “point”, just as in the decimal number system. In that case, the digit in the place immediately to the right of the point has a weight of <math>2^{-1}</math>, or <math>1/2</math>.
The weight for the second column to the right of the point is <math>2^{-2}</math> or <math>1/4</math>. And so on.
If you take the integer binary count of the first table, and ''reflect'' the digits about the binary point, you end up with '''the van der Corput sequence of numbers in base 2'''.
<pre> .0
.1
.01
.11
...</pre>
The third member of the sequence, binary <code>0.01</code>, is therefore <math>0 \times 2^{-1} + 1 \times 2^{-2}</math> or <math>1/4</math>.
<br> [[File:Van der corput distribution.png|400|thumb|right|Distribution of 2500 points each: Van der Corput (top) vs pseudorandom]] Members of the sequence lie within the interval <math>0 \leq x < 1</math>. Points within the sequence tend to be evenly distributed which is a useful trait to have for [[wp:Monte Carlo method|Monte Carlo simulations]].
This sequence is also a superset of the numbers representable by the "fraction" field of [[wp:IEEE 754-1985|an old IEEE floating point standard]]. In that standard, the "fraction" field represented the fractional part of a binary number beginning with "1." e.g. 1.101001101.
'''Hint'''
A ''hint'' at a way to generate members of the sequence is to modify a routine used to change the base of an integer:
<syntaxhighlight lang="python">>>> def base10change(n, base):
digits = []
while n:
n,remainder = divmod(n, base)
digits.insert(0, remainder)
return digits
>>> base10change(11, 2)
[1, 0, 1, 1]</syntaxhighlight>
the above showing that <code>11</code> in decimal is <math>1\times 2^3 + 0\times 2^2 + 1\times 2^1 + 1\times 2^0</math>.<br>
Reflected this would become <code>.1101</code> or <math>1\times 2^{-1} + 1\times 2^{-2} + 0\times 2^{-3} + 1\times 2^{-4}</math>
;Task description:
* Create a function/method/routine that given ''n'', generates the ''n'''th term of the van der Corput sequence in base 2.
* Use the function to compute ''and display'' the first ten members of the sequence. (The first member of the sequence is for ''n''=0).
* As a stretch goal/extra credit, compute and show members of the sequence for bases other than 2.
;See also:
* [http://www.puc-rio.br/marco.ind/quasi_mc.html#low_discrep The Basic Low Discrepancy Sequences]
* [[Non-decimal radices/Convert]]
* [[wp:Van der Corput sequence|Van der Corput sequence]]
<br><br>

View file

@ -0,0 +1,10 @@
F vdc(=n, base = 2)
V (vdc, denom) = (0.0, 1)
L n != 0
denom *= base
(n, V remainder) = divmod(n, base)
vdc += Float(remainder) / denom
R vdc
print((0.<10).map(i -> vdc(i)))
print((0.<10).map(i -> vdc(i, 3)))

View file

@ -0,0 +1,58 @@
* Van der Corput sequence 31/01/2017
VDCS CSECT
USING VDCS,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) prolog
ST R13,4(R15) " <-
ST R15,8(R13) " ->
LR R13,R15 " addressability
ZAP B,=P'2' b=2 (base)
ZAP M,=P'-1' m=-1
SR R6,R6 i=0
LOOPI CH R6,=H'10' do i=0 to 10
BH ELOOPI
AP M,=P'1' w=m+1
ZAP V,=P'0' v=0
ZAP S,=P'1' s=1
ZAP N,M n=m
WHILE CP N,=P'0' do while n<>0
BE EWHILE
MP S,B s=s*b
ZAP PL16,N n
DP PL16,B n/b
ZAP W,PL16+8(8) w=n mod b
MP W,=P'100000' *100000
ZAP PL16,W w
DP PL16,S w/s
ZAP W,PL16(8) w=w/s
AP V,W v=v+(n mod b)*100000/s
ZAP PL16,N n
DP PL16,B n/b
ZAP N,PL16(8) n=n/b
B WHILE
EWHILE XDECO R6,XDEC edit i
MVC PG+0(3),XDEC+9 output i
MVC PG+3(3),=C' 0.'
UNPK Z,V unpack v
OI Z+L'Z-1,X'F0' edit v
MVC PG+6(5),Z+11 output v (v/100000)
XPRNT PG,L'PG print buffer
LA R6,1(R6) i=i+1
B LOOPI
ELOOPI L R13,4(0,R13) epilog
LM R14,R12,12(R13) " restore
XR R15,R15 " rc=0
BR R14 exit
B DS PL8
M DS PL8
V DS PL8
S DS PL8
N DS PL8
W DS PL8 packed
Z DS ZL16 zoned
PL16 DS PL16 packed max
PG DC CL80' ' buffer
XDEC DS CL12 work area for xdeco
YREGS
END VDCS

View file

@ -0,0 +1,38 @@
BEGIN # show members of the van der Corput sequence in various bases #
# translated from the C sample #
# sets num and denom to the numerator and denominator of the nth member #
# of the van der Corput sequence in the specified base #
PROC vc = ( INT nth, base, REF INT num, denom )VOID:
BEGIN
INT p := 0, q := 1, n := nth;
WHILE n /= 0 DO
p *:= base +:= n MOD base;
q *:= base;
n OVERAB base
OD;
num := p;
denom := q;
# reduce the numerrator and denominator by their gcd #
WHILE p /= 0 DO n := p; p := q MOD p; q := n OD;
num OVERAB q;
denom OVERAB q
END # vc # ;
# task #
FOR b FROM 2 TO 5 DO
print( ( "base ", whole( b, 0 ), ":" ) );
FOR i FROM 0 TO 9 DO
INT d, n;
vc( i, b, n, d );
IF n /= 0
THEN print( ( " ", whole( n, 0 ), "/", whole( d, 0 ) ) )
ELSE print( ( " 0" ) )
FI
OD;
print( ( newline ) )
OD
END

View file

@ -0,0 +1,27 @@
# syntax: GAWK -f VAN_DER_CORPUT_SEQUENCE.AWK
# converted from BBC BASIC
BEGIN {
printf("base")
for (i=0; i<=9; i++) {
printf(" %7d",i)
}
printf("\n")
for (base=2; base<=5; base++) {
printf("%-4s",base)
for (i=0; i<=9; i++) {
printf(" %7.5f",vdc(i,base))
}
printf("\n")
}
exit(0)
}
function vdc(n,b, s,v) {
s = 1
while (n) {
s *= b
v += (n % b) / s
n /= b
n = int(n)
}
return(v)
}

View file

@ -0,0 +1,36 @@
INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit
PROC Generate(INT value,base REAL POINTER res)
REAL denom,rbase,r1,r2
IntToReal(0,res)
IntToReal(1,denom)
IntToReal(base,rbase)
WHILE value#0
DO
RealMult(denom,rbase,r1)
RealAssign(r1,denom)
IntToReal(value MOD base,r1)
RealDiv(r1,denom,r2)
RealAdd(res,r2,r1)
RealAssign(r1,res)
value==/base
OD
RETURN
PROC Main()
INT value,base
REAL res
Put(125) PutE() ;clear the screen
FOR base=2 TO 5
DO
PrintF("Base %I:%E",base)
FOR value=0 TO 9
DO
Generate(value,base,res)
PrintR(res) Put(32)
OD
PutE() PutE()
OD
RETURN

View file

@ -0,0 +1,66 @@
package {
import flash.display.Sprite;
import flash.events.Event;
public class VanDerCorput extends Sprite {
public function VanDerCorput():void {
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void {
removeEventListener(Event.ADDED_TO_STAGE, init);
var base2:Vector.<Number> = new Vector.<Number>(10, true);
var base3:Vector.<Number> = new Vector.<Number>(10, true);
var base4:Vector.<Number> = new Vector.<Number>(10, true);
var base5:Vector.<Number> = new Vector.<Number>(10, true);
var base6:Vector.<Number> = new Vector.<Number>(10, true);
var base7:Vector.<Number> = new Vector.<Number>(10, true);
var base8:Vector.<Number> = new Vector.<Number>(10, true);
var i:uint;
for ( i = 0; i < 10; i++ ) {
base2[i] = Math.round( _getTerm(i, 2) * 1000000 ) / 1000000;
base3[i] = Math.round( _getTerm(i, 3) * 1000000 ) / 1000000;
base4[i] = Math.round( _getTerm(i, 4) * 1000000 ) / 1000000;
base5[i] = Math.round( _getTerm(i, 5) * 1000000 ) / 1000000;
base6[i] = Math.round( _getTerm(i, 6) * 1000000 ) / 1000000;
base7[i] = Math.round( _getTerm(i, 7) * 1000000 ) / 1000000;
base8[i] = Math.round( _getTerm(i, 8) * 1000000 ) / 1000000;
}
trace("Base 2: " + base2.join(', '));
trace("Base 3: " + base3.join(', '));
trace("Base 4: " + base4.join(', '));
trace("Base 5: " + base5.join(', '));
trace("Base 6: " + base6.join(', '));
trace("Base 7: " + base7.join(', '));
trace("Base 8: " + base8.join(', '));
}
private function _getTerm(n:uint, base:uint = 2):Number {
var r:Number = 0, p:uint, digit:uint;
var baseLog:Number = Math.log(base);
while ( n > 0 ) {
p = Math.pow( base, uint(Math.log(n) / baseLog) );
digit = n / p;
n %= p;
r += digit / (p * base);
}
return r;
}
}
}

View file

@ -0,0 +1,27 @@
with Ada.Text_IO;
procedure Main is
package Float_IO is new Ada.Text_IO.Float_IO (Float);
function Van_Der_Corput (N : Natural; Base : Positive := 2) return Float is
Value : Natural := N;
Result : Float := 0.0;
Exponent : Positive := 1;
begin
while Value > 0 loop
Result := Result +
Float (Value mod Base) / Float (Base ** Exponent);
Value := Value / Base;
Exponent := Exponent + 1;
end loop;
return Result;
end Van_Der_Corput;
begin
for Base in 2 .. 5 loop
Ada.Text_IO.Put ("Base" & Integer'Image (Base) & ":");
for N in 1 .. 10 loop
Ada.Text_IO.Put (' ');
Float_IO.Put (Item => Van_Der_Corput (N, Base), Exp => 0);
end loop;
Ada.Text_IO.New_Line;
end loop;
end Main;

View file

@ -0,0 +1,14 @@
corput: function [num, base][
result: to :rational 0
b: 1 // base
n: num
while [not? zero? n][
result: result + b * n % base
n: n / base
b: b // base
]
return result
]
loop 2..5 'bs ->
print ["Base" bs ":" join.with:", " to [:string] map 1..10 'z -> corput z bs]

View file

@ -0,0 +1,13 @@
SetFormat, FloatFast, 0.5
for i, v in [2, 3, 4, 5, 6] {
seq .= "Base " v ": "
Loop, 10
seq .= VanDerCorput(A_Index - 1, v) (A_Index = 10 ? "`n" : ", ")
}
MsgBox, % seq
VanDerCorput(n, b, r=0) {
while n
r += Mod(n, b) * b ** -A_Index, n := n // b
return, r
}

View file

@ -0,0 +1,20 @@
10 DEFINT A-Z
20 FOR B=2 TO 5
30 PRINT USING "BASE #:";B;
40 FOR I=0 TO 9
50 P=0: Q=1: N=I
60 IF N=0 GOTO 110
70 P=P*B+N MOD B
80 Q=Q*B
90 N=N\B
100 GOTO 60
110 X=P: Y=Q
120 IF P=0 GOTO 150
130 N=P: P=Q MOD P: Q=N
140 GOTO 120
150 X=X\Q
160 Y=Y\Q
170 IF X=0 THEN PRINT " 0"; ELSE PRINT USING " ##/##";X;Y;
180 NEXT I
190 PRINT
200 NEXT B

View file

@ -0,0 +1,28 @@
function num_base$(number, base)
if base > 9 then
print "base not handled by function"
pause 5
return ""
end if
ans$ = ""
while number <> 0
n = (number mod base)
ans$ = string(n) + ans$
number = number \ base
end while
if ans$ = "" then ans$ = "0"
return "." + ans$
end function
for k = 2 to 5
print "Base = "; k
for l = 0 to 12
print ljust(num_base$(l, k), 6);
next l
print : print
next k
end

View file

@ -0,0 +1,19 @@
@% = &20509
FOR base% = 2 TO 5
PRINT "Base " ; STR$(base%) ":"
FOR number% = 0 TO 9
PRINT FNvdc(number%, base%);
NEXT
PRINT
NEXT
END
DEF FNvdc(n%, b%)
LOCAL v, s%
s% = 1
WHILE n%
s% *= b%
v += (n% MOD b%) / s%
n% DIV= b%
ENDWHILE
= v

View file

@ -0,0 +1,39 @@
get "libhdr"
let corput(n, base, num, denom) be
$( let p = 0 and q = 1
until n=0
$( p := p * base + n rem base
q := q * base
n := n / base
$)
!num := p
!denom := q
until p=0
$( n := p
p := q rem p
q := n
$)
!num := !num / q
!denom := !denom / q
$)
let writefrac(num, denom) be
test num=0
do writes(" 0")
or writef(" %N/%N", num, denom)
let start() be
$( let num = ? and denom = ?
for base=2 to 5
$( writef("base %N:", base)
for i=0 to 9
$( corput(i, base, @num, @denom)
writefrac(num, denom)
$)
wrch('*N')
$)
$)

View file

@ -0,0 +1,39 @@
/*
* Return the _n_th term of the van der Corput sequence.
* Uses the current _ibase_.
*/
define v(n) {
auto c, r, s
s = scale
scale = 0 /* to use integer division */
/*
* c = count digits of n
* r = reverse the digits of n
*/
for (0; n != 0; n /= 10) {
c += 1
r = (10 * r) + (n % 10)
}
/* move radix point to left of digits */
scale = length(r) + 6
r /= 10 ^ c
scale = s
return r
}
t = 10
for (b = 2; b <= 4; b++) {
"base "; b
obase = b
for (i = 0; i < 10; i++) {
ibase = b
" "; v(i)
ibase = t
}
obase = t
}
quit

View file

@ -0,0 +1,26 @@
#include <cmath>
#include <iostream>
double vdc(int n, double base = 2)
{
double vdc = 0, denom = 1;
while (n)
{
vdc += fmod(n, base) / (denom *= base);
n /= base; // note: conversion from 'double' to 'int'
}
return vdc;
}
int main()
{
for (double base = 2; base < 6; ++base)
{
std::cout << "Base " << base << "\n";
for (int n = 0; n < 10; ++n)
{
std::cout << vdc(n, base) << " ";
}
std::cout << "\n\n";
}
}

View file

@ -0,0 +1,127 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace VanDerCorput
{
/// <summary>
/// Computes the Van der Corput sequence for any number base.
/// The numbers in the sequence vary from zero to one, including zero but excluding one.
/// The sequence possesses low discrepancy.
/// Here are the first ten terms for bases 2 to 5:
///
/// base 2: 0 1/2 1/4 3/4 1/8 5/8 3/8 7/8 1/16 9/16
/// base 3: 0 1/3 2/3 1/9 4/9 7/9 2/9 5/9 8/9 1/27
/// base 4: 0 1/4 1/2 3/4 1/16 5/16 9/16 13/16 1/8 3/8
/// base 5: 0 1/5 2/5 3/5 4/5 1/25 6/25 11/25 16/25 21/25
/// </summary>
/// <see cref="http://rosettacode.org/wiki/Van_der_Corput_sequence"/>
public class VanDerCorputSequence: IEnumerable<Tuple<long,long>>
{
/// <summary>
/// Number base for the sequence, which must bwe two or more.
/// </summary>
public int Base { get; private set; }
/// <summary>
/// Maximum number of terms to be returned by iterator.
/// </summary>
public long Count { get; private set; }
/// <summary>
/// Construct a sequence for the given base.
/// </summary>
/// <param name="iBase">Number base for the sequence.</param>
/// <param name="count">Maximum number of items to be returned by the iterator.</param>
public VanDerCorputSequence(int iBase, long count = long.MaxValue) {
if (iBase < 2)
throw new ArgumentOutOfRangeException("iBase", "must be two or greater, not the given value of " + iBase);
Base = iBase;
Count = count;
}
/// <summary>
/// Compute nth term in the Van der Corput sequence for the base specified in the constructor.
/// </summary>
/// <param name="n">The position in the sequence, which may be zero or any positive number.</param>
/// This number is always an integral power of the base.</param>
/// <returns>The Van der Corput sequence value expressed as a Tuple containing a numerator and a denominator.</returns>
public Tuple<long,long> Compute(long n)
{
long p = 0, q = 1;
long numerator, denominator;
while (n != 0)
{
p = p * Base + (n % Base);
q *= Base;
n /= Base;
}
numerator = p;
denominator = q;
while (p != 0)
{
n = p;
p = q % p;
q = n;
}
numerator /= q;
denominator /= q;
return new Tuple<long,long>(numerator, denominator);
}
/// <summary>
/// Compute nth term in the Van der Corput sequence for the given base.
/// </summary>
/// <param name="iBase">Base to use for the sequence.</param>
/// <param name="n">The position in the sequence, which may be zero or any positive number.</param>
/// <returns>The Van der Corput sequence value expressed as a Tuple containing a numerator and a denominator.</returns>
public static Tuple<long, long> Compute(int iBase, long n)
{
var seq = new VanDerCorputSequence(iBase);
return seq.Compute(n);
}
/// <summary>
/// Iterate over the Van Der Corput sequence.
/// The first value in the sequence is always zero, regardless of the base.
/// </summary>
/// <returns>A tuple whose items are the Van der Corput value given as a numerator and denominator.</returns>
public IEnumerator<Tuple<long, long>> GetEnumerator()
{
long iSequenceIndex = 0L;
while (iSequenceIndex < Count)
{
yield return Compute(iSequenceIndex);
iSequenceIndex++;
}
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
class Program
{
static void Main(string[] args)
{
TestBasesTwoThroughFive();
Console.WriteLine("Type return to continue...");
Console.ReadLine();
}
static void TestBasesTwoThroughFive()
{
foreach (var seq in Enumerable.Range(2, 5).Select(x => new VanDerCorputSequence(x, 10))) // Just the first 10 elements of the each sequence
{
Console.Write("base " + seq.Base + ":");
foreach(var vc in seq)
Console.Write(" " + vc.Item1 + "/" + vc.Item2);
Console.WriteLine();
}
}
}
}

View file

@ -0,0 +1,35 @@
#include <stdio.h>
void vc(int n, int base, int *num, int *denom)
{
int p = 0, q = 1;
while (n) {
p = p * base + (n % base);
q *= base;
n /= base;
}
*num = p;
*denom = q;
while (p) { n = p; p = q % p; q = n; }
*num /= q;
*denom /= q;
}
int main()
{
int d, n, i, b;
for (b = 2; b < 6; b++) {
printf("base %d:", b);
for (i = 0; i < 10; i++) {
vc(i, b, &n, &d);
if (n) printf(" %d/%d", n, d);
else printf(" 0");
}
printf("\n");
}
return 0;
}

View file

@ -0,0 +1,38 @@
vc = proc (n, base: int) returns (int, int)
p: int := 0
q: int := 1
while n ~= 0 do
p := p * base + n // base
q := q * base
n := n / base
end
num: int := p
denom: int := q
while p ~= 0 do
p, q := q // p, p
end
return(num/q, denom/q)
end vc
print_frac = proc (po: stream, num, denom: int)
if num=0 then
stream$puts(po, " 0")
else
stream$puts(po, " ")
stream$putright(po, int$unparse(num), 2)
stream$puts(po, "/")
stream$putright(po, int$unparse(denom), 2)
end
end print_frac
start_up = proc ()
po: stream := stream$primary_output()
for base: int in int$from_to(2,5) do
stream$puts(po, "base " || int$unparse(base) || ":")
for i: int in int$from_to(0, 9) do
n, d: int := vc(i, base)
print_frac(po, n, d)
end
stream$putl(po, "")
end
end start_up

View file

@ -0,0 +1,25 @@
(defn van-der-corput
"Get the nth element of the van der Corput sequence."
([n]
;; Default base = 2
(van-der-corput n 2))
([n base]
(let [s (/ 1 base)] ;; A multiplicand to shift to the right of the decimal.
;; We essentially want to reverse the digits of n and put them after the
;; decimal point. So, we repeatedly pull off the lowest digit of n, scale
;; it to the right of the decimal point, and accumulate that.
(loop [sum 0
n n
scale s]
(if (zero? n)
sum ;; Base case: no digits left, so we're done.
(recur (+ sum (* (rem n base) scale)) ;; Accumulate the least digit
(quot n base) ;; Drop a digit of n
(* scale s))))))) ;; Move farther past the decimal
(clojure.pprint/print-table
(cons :base (range 10)) ;; column headings
(for [base (range 2 6)] ;; rows
(into {:base base}
(for [n (range 10)] ;; table entries
[n (van-der-corput n base)]))))

View file

@ -0,0 +1,11 @@
(defun van-der-Corput (n base)
(loop for d = 1 then (* d base) while (<= d n)
finally
(return (/ (parse-integer
(reverse (write-to-string n :base base))
:radix base)
d))))
(loop for base from 2 to 5 do
(format t "Base ~a: ~{~6a~^~}~%" base
(loop for i to 10 collect (van-der-Corput i base))))

View file

@ -0,0 +1,55 @@
include "cowgol.coh";
sub vc(n: uint16, base: uint16): (num: uint16, denom: uint16) is
var p: uint16 := 0;
var q: uint16 := 1;
while n != 0 loop
p := p * base + n % base;
q := q * base;
n := n / base;
end loop;
num := p;
denom := q;
while p != 0 loop
n := p;
p := q % p;
q := n;
end loop;
num := num / q;
denom := denom / q;
end sub;
sub printfrac(num: uint16, denom: uint16) is
if num == 0 then
print(" 0");
else
print(" ");
print_i16(num);
print("/");
print_i16(denom);
end if;
end sub;
var i: uint16;
var base: uint16;
var num: uint16;
var denom: uint16;
base := 2;
while base < 6 loop
print("base ");
print_i16(base);
print(":");
i := 0;
while i < 10 loop
(num, denom) := vc(i, base);
printfrac(num, denom);
i := i + 1;
end loop;
print_nl();
base := base + 1;
end loop;

View file

@ -0,0 +1,16 @@
double vdc(int n, in double base=2.0) pure nothrow @safe @nogc {
double vdc = 0.0, denom = 1.0;
while (n) {
denom *= base;
vdc += (n % base) / denom;
n /= base;
}
return vdc;
}
void main() {
import std.stdio, std.algorithm, std.range;
foreach (immutable b; 2 .. 6)
writeln("\nBase ", b, ": ", 10.iota.map!(n => vdc(n, b)));
}

View file

@ -0,0 +1,39 @@
function VanDerCorput(N,Base: integer): double;
{Calculate binary value for numbers right of decimal}
var Value,Exponent,Digit: integer;
begin
Value:= N; Result:= 0; Exponent:= -1;
{D1 * Base^-1 + D2 * Base^-2 + D3 * Base^-3}
while Value > 0 do
begin
{Get digit in specified base}
Digit:=Value mod Base;
{Digit * Base^-Exponent}
Result:=Result + Digit * Power(Base,Exponent);
{Divide by base to put next digit in place}
Value:= Value div Base;
{Next exponent}
Dec(Exponent);
end;
end;
procedure ShowVanDerCorput(Memo: TMemo);
{Show Vander Coput numbers for bases 2..8 and items 1..9 }
var Base,N: integer;
var V: double;
var S: string;
begin
S:='';
for Base:=2 to 8 do
begin
S:=S+Format('Base %D:',[Base]);
for N:=1 to 10 do
begin
V:=VanDerCorput(N,Base);
S:=S+Format(' %1.5f',[V]);
end;
S:=S+CRLF;
end;
Memo.Lines.Add(S);
end;

View file

@ -0,0 +1,109 @@
[Van der Corput sequence for Rosetta Code.
EDSAC solution, Initial Orders 2.]
[Library subroutine M3 - prints header at load time and is then overwritten.
Here, the last character sets the teleprinter to figures.]
PFGKIFAFRDLFUFOFE@A6FG@E8FEZPF
*VAN!DER!CORPUT!SEQUENCE@&#17A*BIT!!!#35A*BIT@&#
..PZ [blank tape then re-sync]
[Define load addresses]
T55K P100F [V parameter: van der Corput subroutines]
T51K P64F [G parameter: print subroutine]
T47K P400F [M parameter: main routine]
[Subroutines to return n'th element of van der Corput sequence.
17-bit version: Call by GV, pass n in 0F (not preserved), result in 4F.
35-bit version: Call by G1V, pass n in 0D (not preserved), result in 4D.]
E25K TV GK
G2@ [jump to 17-bit version]
G25@ [jump to 35-bit version]
[17-bit version.
On EDSAC, it's a matter of reversing the bits after the binary point
To save time, we use a table to reverse the 16 bits in groups of 4.]
[2] A3F T24@ [plant return link as usual]
H5 6@ [set mult reg to 0...01111 binary]
A55@ T4F [set marker bit 0...01 in result]
[7] A4F L4F T4F [shift result 4 left]
CF [acc := next 4 bits of n]
LD [shift into address field]
A58@ T14@ [plant A order to load from table]
[14] AF [{planted) load bits from table]
A4F [add to result]
G22@ [jump out if marker bit has reached sign bit]
T4F [update result]
AF R4F TF [shift n 4 right]
E7@ [always loop back]
[22] S57@ [done, remove marker bit]
T4F [store final result]
[24] ZF [(planted) jump to return to caller]
[35-bit version. Very similar to the 17-bit version, except that
after reversing 8 groups of 4, there are 2 bits left over,
which require separate treatment.]
[25] A3F T54@ [plant return link as usual]
H56@ [set mult reg to 0...01111 binary]
YF L2F [set marker bit 0...0100 in result]
[30] L4F T4D [shift result 4 left]
CF LD A58@ T36@ AF A4F T4F [update from table as in 17-bit version]
ADR4FTD [shift n 4 right]
A4D [load result]
E30@ [if marker bit hasn't reached sign bit, loop back]
[Last 2 bits]
[44] L1FT4D [shift result 2 right]
CF LD A58@ T50@ [plant A order as in 17-bit version]
[50] AF [Planted) load bits from table]
R1F A4F T4F [shift table entry 2 right and add to result]
[54] ZF [(planted) jump to return to caller]
[Constants]
[55] PD [17-bit 1]
[56] P7D [17-bit 15]
[57] K4096F [17-bit 10...0 binary]
[58] A59@ [order to load from table{0}]
[Table to reverse group of 4 bits, e.g. table{0010b} = 0100b]
[59] PFP4FP2FP6FP1FP5FP3FP7FPDP4DP2DP6DP1DP5DP3DP7D
[Library subroutine P1 to print number in range 0 <= x < 1.
Caller must print leading '0.' if required. 21 storage locations.]
E25K TG
GKA18@U17@S20@T5@H19@PFT5@VDUFOFFFSFL4FTDA5@A2FG6@EFU3FJFM1F
[Main routine]
E25K TM GK
[0] PF PF [n, 35 bits, must be at even address]
[2] PF [negative count of terms]
[3] P10F [<=== EDIT number of terms, in address field]
[4] PD [17-bit integer 1]
[5] MF [dot (in figures mode)]
[6] @F [carriage return]
[7] &F [line feed]
[8] !F [space character]
[9] K4096F [null character]
[Enter with acc = 0]
[10] T#@ [n := 0]
S3@ T2@ [initialize negative count]
[13] A@ TF [pass 17-bit n in 0F]
[15] A15@ GV [call 17-bit van der Corput routine]
TD [clear 0D, including sandwich bit]
A4F T1F [extend 17-bit result to 35 bits in 0D]
O4@ O5@ [print '0.']
[22] A22@ GG P5F [print result to 5 decimals]
O8@ O8@ [print 2 spaces]
A#@ TD [pass 35-bit n in 0D]
[29] A29@ G1V [call 35-bit van der Corput routine]
A4D TD [pass result in 0D]
O4@ O5@ [print '0.']
[35] A35@ GG P10F [print result to 10 decimals]
O6@ O7@ [print CR LF]
A2@ A2F [inc negative count]
E48@ [jump out if count = 0]
T2@ [update count]
A@ A4@ T@ [inc n]
E13@ [loop back]
[48] O9@ [print null to flush teleprinter buffer]
ZF [stop]
E10Z [define entry point]
PF [acc = 0 on entry]
[end]

View file

@ -0,0 +1,27 @@
PROGRAM VAN_DER_CORPUT
!
! for rosettacode.org
!
PROCEDURE VDC(N%,B%->RES)
LOCAL V,S%
S%=1
WHILE N%>0 DO
S%*=B%
V+=(N% MOD B%)/S%
N%=N% DIV B%
END WHILE
RES=V
END PROCEDURE
BEGIN
FOR BASE%=2 TO 5 DO
PRINT("Base";STR$(BASE%);":")
FOR NUMBER%=0 TO 9 DO
VDC(NUMBER%,BASE%->RES)
WRITE("#.##### ";RES;)
END FOR
PRINT
END FOR
END PROGRAM

View file

@ -0,0 +1,18 @@
proc vdc b n . v .
s = 1
v = 0
while n > 0
s *= b
m = n mod b
v += m / s
n = n div b
.
.
for b = 2 to 5
write "base " & b & ":"
for n range0 10
call vdc b n v
write " " & v
.
print ""
.

View file

@ -0,0 +1,11 @@
open random number list
vdc bs n = vdc' 0.0 1.0 n
where vdc' v d n
| n > 0 = vdc' v' d' n'
| else = v
where
d' = d * bs
rem = n % bs
n' = truncate (n / bs)
v' = v + rem / d'

View file

@ -0,0 +1 @@
take 10 <| map' (vdc 2.0) [1..]

View file

@ -0,0 +1,34 @@
defmodule Van_der_corput do
def sequence( n, base \\ 2 ) do
"0." <> (Integer.to_string(n, base) |> String.reverse )
end
def float( n, base \\ 2 ) do
Integer.digits(n, base) |> Enum.reduce(0, fn i,acc -> (i + acc) / base end)
end
def fraction( n, base \\ 2 ) do
str = Integer.to_string(n, base) |> String.reverse
denominator = Enum.reduce(1..String.length(str), 1, fn _,acc -> acc*base end)
reduction( String.to_integer(str, base), denominator )
end
defp reduction( 0, _ ), do: "0"
defp reduction( numerator, denominator ) do
gcd = gcd( numerator, denominator )
"#{ div(numerator, gcd) }/#{ div(denominator, gcd) }"
end
defp gcd( a, 0 ), do: a
defp gcd( a, b ), do: gcd( b, rem(a, b) )
end
funs = [ {"Float(Base):", &Van_der_corput.sequence/2},
{"Float(Decimal):", &Van_der_corput.float/2 },
{"Fraction:", &Van_der_corput.fraction/2} ]
Enum.each(funs, fn {title, fun} ->
IO.puts title
Enum.each(2..5, fn base ->
IO.puts " Base #{ base }: #{ Enum.map_join(0..9, ", ", &fun.(&1, base)) }"
end)
end)

View file

@ -0,0 +1,23 @@
-module( van_der_corput ).
-export( [sequence/1, sequence/2, task/0] ).
sequence( N ) -> sequence( N, 2 ).
sequence( 0, _Base ) -> 0.0;
sequence( N, Base ) -> erlang:list_to_float( "0." ++ lists:flatten([erlang:integer_to_list(X) || X <- sequence_loop(N, Base)]) ).
task() -> [task(X) || X <- lists:seq(2, 5)].
sequence_loop( 0, _Base ) -> [];
sequence_loop( N, Base ) ->
New_n = N div Base,
Digit = N rem Base,
[Digit | sequence_loop( New_n, Base )].
task( Base ) ->
io:fwrite( "Base ~p:", [Base] ),
[io:fwrite( " ~p", [sequence(X, Base)] ) || X <- lists:seq(0, 9)],
io:fwrite( "~n" ).

View file

@ -0,0 +1,20 @@
function vdc(integer n, atom base)
atom vdc, denom, rem
vdc = 0
denom = 1
while n do
denom *= base
rem = remainder(n,base)
n = floor(n/base)
vdc += rem / denom
end while
return vdc
end function
for i = 2 to 5 do
printf(1,"Base %d\n",i)
for j = 0 to 9 do
printf(1,"%g ",vdc(j,i))
end for
puts(1,"\n\n")
end for

View file

@ -0,0 +1,16 @@
open System
let vdc n b =
let rec loop n denom acc =
if n > 0l then
let m, remainder = Math.DivRem(n, b)
loop m (denom * b) (acc + (float remainder) / (float (denom * b)))
else acc
loop n 1 0.0
[<EntryPoint>]
let main argv =
printfn "%A" [ for n in 0 .. 9 -> (vdc n 2) ]
printfn "%A" [ for n in 0 .. 9 -> (vdc n 5) ]
0

View file

@ -0,0 +1,15 @@
USING: formatting fry io kernel math math.functions math.parser
math.ranges sequences ;
IN: rosetta-code.van-der-corput
: vdc ( n base -- x )
[ >base string>digits <reversed> ]
[ nip '[ 1 + neg _ swap ^ * ] ] 2bi map-index sum ;
: vdc-demo ( -- )
2 5 [a,b] [
dup "Base %d: " printf 10 <iota>
[ swap vdc "%-5u " printf ] with each nl
] each ;
MAIN: vdc-demo

View file

@ -0,0 +1,10 @@
: fvdc ( base n -- f )
0e 1e ( F: vdc denominator )
begin dup while
over s>d d>f f*
over /mod ( base rem n )
swap s>d d>f fover f/
frot f+ fswap
repeat 2drop fdrop ;
: test 10 0 do 2 i fvdc cr f. loop ;

View file

@ -0,0 +1,35 @@
FUNCTION VDC(N,BASE) !Calculates a Van der Corput number...
Converts 1234 in decimal to 4321 in V, and P = 10000.
INTEGER N !For this integer,
INTEGER BASE !In this base.
INTEGER I !A copy of N that can be damaged.
INTEGER P !Successive powers of BASE.
INTEGER V !Accumulates digits.
P = 1 ! = BASE**0
V = 0 !Start with no digits, as if N = 0.
I = N !Here we go.
DO WHILE (I .NE. 0) !While something remains,
V = V*BASE + MOD(I,BASE) !Extract its low-order digit.
I = I/BASE !Reduce it by a power.
P = P*BASE !And track the power.
END DO !Thus extract the digits in reverse order: right-to-left.
VDC = V/FLOAT(P) !The power is one above the highest digit.
END FUNCTION VDC !Numerology is weird.
PROGRAM POKE
INTEGER FIRST,LAST !Might as well document some constants.
PARAMETER (FIRST = 0,LAST = 9) !Thus, the first ten values.
INTEGER I,BASE !Steppers.
REAL VDC !Stop the compiler moaning about undeclared items.
WRITE (6,1) FIRST,LAST,(I, I = FIRST,LAST) !Announce.
1 FORMAT ("Calculates values ",I0," to ",I0," of the ",
1 "Van der Corput sequence, in various bases."/
2 "Base",666I9)
DO BASE = 2,13 !A selection of bases.
WRITE (6,2) BASE,(VDC(I,BASE), I = FIRST,LAST) !Show the specified span.
2 FORMAT (I4,666F9.6) !Aligns with FORMAT 1.
END DO !On to the next base.
END

View file

@ -0,0 +1,42 @@
' version 03-12-2016
' compile with: fbc -s console
Function num_base(number As ULongInt, _base_ As UInteger) As String
If _base_ > 9 Then
Print "base not handled by function"
Sleep 5000
Return ""
End If
Dim As ULongInt n
Dim As String ans
While number <> 0
n = number Mod _base_
ans = Str(n) + ans
number = number \ _base_
Wend
If ans = "" Then ans = "0"
Return "." + ans
End Function
' ------=< MAIN >=------
Dim As ULong k, l
For k = 2 To 5
Print "Base = "; k
For l = 0 To 12
Print left(num_base(l, k) + " ",6);
Next
Print : print
Next
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End

View file

@ -0,0 +1,40 @@
package main
import "fmt"
func v2(n uint) (r float64) {
p := .5
for n > 0 {
if n&1 == 1 {
r += p
}
p *= .5
n >>= 1
}
return
}
func newV(base uint) func(uint) float64 {
invb := 1 / float64(base)
return func(n uint) (r float64) {
p := invb
for n > 0 {
r += p * float64(n%base)
p *= invb
n /= base
}
return
}
}
func main() {
fmt.Println("Base 2:")
for i := uint(0); i < 10; i++ {
fmt.Println(i, v2(i))
}
fmt.Println("Base 3:")
v3 := newV(3)
for i := uint(0); i < 10; i++ {
fmt.Println(i, v3(i))
}
}

View file

@ -0,0 +1,54 @@
import Data.Ratio (Rational(..), (%), numerator, denominator)
import Data.List (unfoldr)
import Text.Printf (printf)
-- A wrapper type for Rationals to make them look nicer when we print them.
newtype Rat =
Rat Rational
instance Show Rat where
show (Rat n) = show (numerator n) <> ('/' : show (denominator n))
-- Convert a list of base b digits to its corresponding number.
-- We assume the digits are valid base b numbers and that
-- their order is from least to most significant.
digitsToNum :: Integer -> [Integer] -> Integer
digitsToNum b = foldr1 (\d acc -> b * acc + d)
-- Convert a number to the list of its base b digits.
-- The order will be from least to most significant.
numToDigits :: Integer -> Integer -> [Integer]
numToDigits _ 0 = [0]
numToDigits b n = unfoldr step n
where
step 0 = Nothing
step m =
let (q, r) = m `quotRem` b
in Just (r, q)
-- Return the n'th element in the base b van der Corput sequence.
-- The base must be ≥ 2.
vdc :: Integer -> Integer -> Rat
vdc b n
| b < 2 = error "vdc: base must be ≥ 2"
| otherwise =
let ds = reverse $ numToDigits b n
in Rat (digitsToNum b ds % b ^ length ds)
-- Each base followed by a specified range of van der Corput numbers.
printVdcRanges :: ([Integer], [Integer]) -> IO ()
printVdcRanges (bases, nums) =
mapM_
putStrLn
[ printf "Base %d:" b <> concatMap (printf " %5s" . show) rs
| b <- bases
, let rs = map (vdc b) nums ]
main :: IO ()
main = do
-- Small bases:
printVdcRanges ([2, 3, 4, 5], [0 .. 9])
putStrLn []
-- Base 123:
printVdcRanges ([123], [50,100 .. 300])

View file

@ -0,0 +1,17 @@
procedure main(A)
base := integer(get(A)) | 2
every writes(round(vdc(0 to 9,base),10)," ")
write()
end
procedure vdc(n, base)
e := 1.0
x := 0.0
while x +:= 1(((0 < n) % base) / (e *:= base), n /:= base)
return x
end
procedure round(n,d)
places := 10 ^ d
return real(integer(n*places + 0.5)) / places
end

View file

@ -0,0 +1,6 @@
procedure vdc(n, base)
s1 := create |((0 < 1(.n, n /:= base)) % base)
s2 := create 2(e := 1.0, |(e *:= base))
every (result := 0) +:= |s1() / s2()
return result
end

View file

@ -0,0 +1 @@
vdc=: ([ %~ %@[ #. #.inv)"0 _

View file

@ -0,0 +1,9 @@
2 vdc i.10 NB. 1st 10 nums of Van der Corput sequence in base 2
0 0.5 0.25 0.75 0.125 0.625 0.375 0.875 0.0625 0.5625
2x vdc i.10 NB. as above but using rational nums
0 1r2 1r4 3r4 1r8 5r8 3r8 7r8 1r16 9r16
2 3 4 5x vdc i.10 NB. 1st 10 nums of Van der Corput sequence in bases 2 3 4 5
0 1r2 1r4 3r4 1r8 5r8 3r8 7r8 1r16 9r16
0 1r3 2r3 1r9 4r9 7r9 2r9 5r9 8r9 1r27
0 1r4 1r2 3r4 1r16 5r16 9r16 13r16 1r8 3r8
0 1r5 2r5 3r5 4r5 1r25 6r25 11r25 16r25 21r25

View file

@ -0,0 +1,17 @@
public class VanDerCorput{
public static double vdc(int n){
double vdc = 0;
int denom = 1;
while(n != 0){
vdc += n % 2.0 / (denom *= 2);
n /= 2;
}
return vdc;
}
public static void main(String[] args){
for(int i = 0; i <= 10; i++){
System.out.println(vdc(i));
}
}
}

View file

@ -0,0 +1,16 @@
# vdc(base) converts an input decimal integer to a decimal number based on the van der
# Corput sequence using base 'base', e.g. (4 | vdc(2)) is 0.125.
#
def vdc(base):
# The helper function converts a stream of residuals to a decimal,
# e.g. if base is 2, then decimalize( (0,0,1) ) yields 0.125
def decimalize(stream):
reduce stream as $d # state: [accumulator, power]
( [0, 1/base];
.[1] as $power | [ .[0] + ($d * $power), $power / base] )
| .[0];
if . == 0 then 0
else decimalize(recurse( if . == 0 then empty else ./base | floor end ) % base)
end ;

View file

@ -0,0 +1,5 @@
def round(n):
(if . < 0 then -1 else 1 end) as $s
| $s*10*.*n | if (floor%10)>4 then (.+5) else . end | ./10 | floor/n | .*$s;
range(2;6) | . as $base | "Base \(.): \( [ range(0;11) | vdc($base)|round(1000) ] )"

View file

@ -0,0 +1,5 @@
$ jq -n -f -c -r van_der_corput_sequence.jq
Base 2: [0,0.5,0.25,0.75,0.125,0.625,0.375,0.875,0.063,0.563,0.313]
Base 3: [0,0.333,0.667,0.111,0.444,0.778,0.222,0.556,0.889,0.037,0.37]
Base 4: [0,0.25,0.5,0.75,0.063,0.313,0.563,0.813,0.125,0.375,0.625]
Base 5: [0,0.2,0.4,0.6,0.8,0.04,0.24,0.44,0.64,0.84,0.08]

View file

@ -0,0 +1,9 @@
using Printf
vandercorput(num::Integer, base::Integer) = sum(d * Float64(base) ^ -ex for (ex, d) in enumerate(digits(num, base = base)))
for base in 2:9
@printf("%10s %i:", "Base", base)
for num in 0:9 @printf("%7.3f", vandercorput(num, base)) end
println(" [...]")
end

View file

@ -0,0 +1,34 @@
// version 1.1.2
data class Rational(val num: Int, val denom: Int)
fun vdc(n: Int, base: Int): Rational {
var p = 0
var q = 1
var nn = n
while (nn != 0) {
p = p * base + nn % base
q *= base
nn /= base
}
val num = p
val denom = q
while (p != 0) {
nn = p
p = q % p
q = nn
}
return Rational(num / q, denom / q)
}
fun main(args: Array<String>) {
for (b in 2..5) {
print("base $b:")
for (i in 0..9) {
val(num, denom) = vdc(i, b)
if (num != 0) print(" $num/$denom")
else print(" 0")
}
println()
}
}

View file

@ -0,0 +1,13 @@
function vdc(n, base)
local digits = {}
while n ~= 0 do
local m = math.floor(n / base)
table.insert(digits, n - m * base)
n = m
end
m = 0
for p, d in pairs(digits) do
m = m + math.pow(base, -p) * d
end
return m
end

View file

@ -0,0 +1,6 @@
function x = corput (n)
b = dec2bin(1:n)-'0'; % generate sequence of binary numbers from 1 to n
l = size(b,2); % get number of binary digits
w = (1:l)-l-1; % 2.^w are the weights
x = b * ( 2.^w'); % matrix times vector multiplication for
end;

View file

@ -0,0 +1,21 @@
Halton:=proc(n,b)
local i:=n,k:=1,s:=0,r;
while i>0 do
k/=b;
i:=iquo(i,b,'r');
s+=k*r
od;
s
end;
map(Halton,[$1..10],2);
# [1/2, 1/4, 3/4, 1/8, 5/8, 3/8, 7/8, 1/16, 9/16, 5/16]
map(Halton,[$1..10],3);
# [1/3, 2/3, 1/9, 4/9, 7/9, 2/9, 5/9, 8/9, 1/27, 10/27]
map(Halton,[$1..10],4);
# [1/4, 1/2, 3/4, 1/16, 5/16, 9/16, 13/16, 1/8, 3/8, 5/8]
map(Halton,[$1..10],5);
[1/5, 2/5, 3/5, 4/5, 1/25, 6/25, 11/25, 16/25, 21/25, 2/25]

View file

@ -0,0 +1,7 @@
VanDerCorput[n_,base_:2]:=Table[
FromDigits[{Reverse[IntegerDigits[k,base]],0},base],
{k,n}]
VanDerCorput[10,2]
VanDerCorput[10,3]
VanDerCorput[10,4]
VanDerCorput[10,5]

View file

@ -0,0 +1,11 @@
/* convert a decimal integer to a list of digits in base `base' */
dec2digits(d, base):= block([digits: []],
while (d>0) do block([newdi: mod(d, base)],
digits: cons(newdi, digits),
d: round( (d - newdi) / base)),
digits)$
dec2digits(123, 10);
/* [1, 2, 3] */
dec2digits( 8, 2);
/* [1, 0, 0, 0] */

View file

@ -0,0 +1,9 @@
/* convert a list of digits in base `base' to a decimal integer */
digits2dec(l, base):= block([s: 0, po: 1],
for di in reverse(l) do (s: di*po + s, po: po*base),
s)$
digits2dec([1, 2, 3], 10);
/* 123 */
digits2dec([1, 0, 0, 0], 2);
/* 8 */

View file

@ -0,0 +1,19 @@
vdc(n, base):= makelist(
digits2dec(
dec2digits(k, base),
1/base) / base,
k, n);
vdc(10, 2);
/*
1 1 3 1 5 3 7 1 9 5
(%o123) [-, -, -, -, -, -, -, --, --, --]
2 4 4 8 8 8 8 16 16 16
*/
vdc(10, 5);
/*
1 2 3 4 1 6 11 16 21 2
(%o124) [-, -, -, -, --, --, --, --, --, --]
5 5 5 5 25 25 25 25 25 25
*/

View file

@ -0,0 +1,21 @@
/* 11 in decimal is */
digits: digits2dec([box(1), box(0), box(1), box(1)], box(2));
aux: expand(digits2dec(digits, 1/base) / base)$
simp: false$
/* reflected this would become ... */
subst(box(2), base, aux);
simp: true$
/*
3 2
""" """ """ """ """ """ """
(%o126) "2" "1" + "2" "0" + "2" "1" + "1"
""" """ """ """ """ """ """
- 4 - 3 - 2 - 1
""" """ """ """ """ """ """ """
(%o129) "1" "2" + "0" "2" + "1" "2" + "1" "2"
""" """ """ """ """ """ """ """
*/

View file

@ -0,0 +1,50 @@
MODULE Sequence;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
PROCEDURE vc(n,base : INTEGER; VAR num,denom : INTEGER);
VAR p,q : INTEGER;
BEGIN
p := 0;
q := 1;
WHILE n#0 DO
p := p * base + (n MOD base);
q := q * base;
n := n DIV base
END;
num := p;
denom := q;
WHILE p#0 DO
n := p;
p := q MOD p;
q := n
END;
num := num DIV q;
denom := denom DIV q
END vc;
VAR
buf : ARRAY[0..31] OF CHAR;
d,n,i,b : INTEGER;
BEGIN
FOR b:=2 TO 5 DO
FormatString("base %i:", buf, b);
WriteString(buf);
FOR i:=0 TO 9 DO
vc(i,b,n,d);
IF n#0 THEN
FormatString(" %i/%i", buf, n, d);
WriteString(buf)
ELSE
WriteString(" 0")
END
END;
WriteLn
END;
ReadChar
END Sequence.

View file

@ -0,0 +1,16 @@
import rationals, strutils, sugar
type Fract = Rational[int]
proc corput(n: int; base: Positive): Fract =
result = 0.toRational
var b = 1 // base
var n = n
while n != 0:
result += n mod base * b
n = n div base
b /= base
for base in 2..5:
let list = collect(newSeq, for n in 1..10: corput(n, base))
echo "Base $#: ".format(base), list.join(" ")

View file

@ -0,0 +1,3 @@
VdC(n)=n=binary(n);sum(i=1,#n,if(n[i],1.>>(#n+1-i)));
VdC(n)=sum(i=1,#binary(n),if(bittest(n,i-1),1.>>i)); \\ Alternate approach
vector(10,n,VdC(n))

View file

@ -0,0 +1,18 @@
vdcb: procedure (an) returns (bit (31)); /* 6 July 2012 */
declare an fixed binary (31);
declare (n, i) fixed binary (31);
declare v bit (31) varying;
n = an; v = ''b;
do i = 1 by 1 while (n > 0);
if iand(n, 1) = 1 then v = v || '1'b; else v = v || '0'b;
n = isrl(n, 1);
end;
return (v);
end vdcb;
declare i fixed binary (31);
do i = 0 to 10;
put skip list ('0.' || vdcb(i));
end;

View file

@ -0,0 +1,88 @@
Program VanDerCorput;
{$IFDEF FPC}
{$MODE DELPHI}
{$ELSE}
{$APPTYPE CONSOLE}
{$ENDIF}
type
tvdrCallback = procedure (nom,denom: NativeInt);
{ Base=2
function rev2(n,Pot:NativeUint):NativeUint;
var
r : Nativeint;
begin
r := 0;
while Pot > 0 do
Begin
r := r shl 1 OR (n AND 1);
n := n shr 1;
dec(Pot);
end;
rev2 := r;
end;
}
function reverse(n,base,Pot:NativeUint):NativeUint;
var
r,c : Nativeint;
begin
r := 0;
//No need to test n> 0 in this special case, n starting in upper half
while Pot > 0 do
Begin
c := n div base;
r := n+(r-c)*base;
n := c;
dec(Pot);
end;
reverse := r;
end;
procedure VanDerCorput(base,count:NativeUint;f:tvdrCallback);
//calculates count nominater and denominater of Van der Corput sequence
// to base
var
Pot,
denom,nom,
i : NativeUint;
Begin
denom := 1;
Pot := 0;
while count > 0 do
Begin
IF Pot = 0 then
f(0,1);
//start in upper half
i := denom;
inc(Pot);
denom := denom *base;
repeat
nom := reverse(i,base,Pot);
IF count > 0 then
f(nom,denom)
else
break;
inc(i);
dec(count);
until i >= denom;
end;
end;
procedure vdrOutPut(nom,denom: NativeInt);
Begin
write(nom,'/',denom,' ');
end;
var
i : NativeUint;
Begin
For i := 2 to 5 do
Begin
write(' Base ',i:2,' :');
VanDerCorput(i,9,@vdrOutPut);
writeln;
end;
end.

View file

@ -0,0 +1,15 @@
sub vdc {
my @value = shift;
my $base = shift // 2;
use integer;
push @value, $value[-1] / $base while $value[-1] > 0;
my ($x, $sum) = (1, 0);
no integer;
$sum += ($_ % $base) / ($x *= $base) for @value;
return $sum;
}
for my $base ( 2 .. 5 ) {
print "base $base: ", join ' ', map { vdc($_, $base) } 0 .. 10;
print "\n";
}

View file

@ -0,0 +1,46 @@
(phixonline)-->
<span style="color: #008080;">enum</span> <span style="color: #000000;">BASE</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">FRAC</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">DECIMAL</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">DESC</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"Base"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Fraction"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Decimal"</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">vdc</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">atom</span> <span style="color: #000000;">base</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">flag</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">object</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">num</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">denom</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">digit</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">g</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">n</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">denom</span> <span style="color: #0000FF;">*=</span> <span style="color: #000000;">base</span>
<span style="color: #000000;">digit</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">remainder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">base</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">/</span><span style="color: #000000;">base</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">flag</span><span style="color: #0000FF;">=</span><span style="color: #000000;">BASE</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">digit</span><span style="color: #0000FF;">+</span><span style="color: #008000;">'0'</span>
<span style="color: #008080;">else</span>
<span style="color: #000000;">num</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">num</span><span style="color: #0000FF;">*</span><span style="color: #000000;">base</span><span style="color: #0000FF;">+</span><span style="color: #000000;">digit</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">flag</span><span style="color: #0000FF;">=</span><span style="color: #000000;">FRAC</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">g</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">gcd</span><span style="color: #0000FF;">(</span><span style="color: #000000;">num</span><span style="color: #0000FF;">,</span><span style="color: #000000;">denom</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">num</span><span style="color: #0000FF;">/</span><span style="color: #000000;">g</span><span style="color: #0000FF;">,</span><span style="color: #000000;">denom</span><span style="color: #0000FF;">/</span><span style="color: #000000;">g</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">elsif</span> <span style="color: #000000;">flag</span><span style="color: #0000FF;">=</span><span style="color: #000000;">DECIMAL</span> <span style="color: #008080;">then</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">num</span><span style="color: #0000FF;">/</span><span style="color: #000000;">denom</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">return</span> <span style="color: #0000FF;">{</span><span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">?</span><span style="color: #008000;">"0"</span><span style="color: #0000FF;">:</span><span style="color: #008000;">"0."</span><span style="color: #0000FF;">&</span><span style="color: #000000;">res</span><span style="color: #0000FF;">)}</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">show_vdc</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">flag</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">string</span> <span style="color: #000000;">fmt</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">object</span> <span style="color: #000000;">v</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">2</span> <span style="color: #008080;">to</span> <span style="color: #000000;">5</span> <span style="color: #008080;">do</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s %d: "</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">DESC</span><span style="color: #0000FF;">[</span><span style="color: #000000;">flag</span><span style="color: #0000FF;">],</span><span style="color: #000000;">i</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">to</span> <span style="color: #000000;">9</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">v</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">vdc</span><span style="color: #0000FF;">(</span><span style="color: #000000;">j</span><span style="color: #0000FF;">,</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">flag</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">flag</span><span style="color: #0000FF;">=</span><span style="color: #000000;">FRAC</span> <span style="color: #008080;">and</span> <span style="color: #000000;">v</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"0 "</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">else</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">fmt</span><span style="color: #0000FF;">,</span><span style="color: #000000;">v</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000000;">show_vdc</span><span style="color: #0000FF;">(</span><span style="color: #000000;">BASE</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s "</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">show_vdc</span><span style="color: #0000FF;">(</span><span style="color: #000000;">FRAC</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%d/%d "</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">show_vdc</span><span style="color: #0000FF;">(</span><span style="color: #000000;">DECIMAL</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%g "</span><span style="color: #0000FF;">)</span>
<!--

View file

@ -0,0 +1,14 @@
(scl 6)
(de vdc (N B)
(default B 2)
(let (R 0 A 1.0)
(until (=0 N)
(inc 'R (* (setq A (/ A B)) (% N B)))
(setq N (/ N B)) )
R ) )
(for B (2 3 4)
(prinl "Base: " B)
(for N (range 0 9)
(prinl N ": " (round (vdc N B) 4)) ) )

View file

@ -0,0 +1,41 @@
% vdc( N, Base, Out )
% Out = the Van der Corput representation of N in given Base
vdc( 0, _, [] ).
vdc( N, Base, Out ) :-
Nr is mod(N, Base),
Nq is N // Base,
vdc( Nq, Base, Tmp ),
Out = [Nr|Tmp].
% Writes every element of a list to stdout; no newlines
write_list( [] ).
write_list( [H|T] ) :-
write( H ),
write_list( T ).
% Writes the Nth Van der Corput item.
print_vdc( N, Base ) :-
vdc( N, Base, Lst ),
write('0.'),
write_list( Lst ).
print_vdc( N ) :-
print_vdc( N, 2 ).
% Prints the first N+1 elements of the Van der Corput
% sequence, each to its own line
print_some( 0, _ ) :-
write( '0.0' ).
print_some( N, Base ) :-
M is N - 1,
print_some( M, Base ),
nl,
print_vdc( N, Base ).
print_some( N ) :-
print_some( N, 2 ).
test :-
writeln('First 10 members in base 2:'),
print_some( 9 ),
nl,
write('7th member in base 4 (stretch goal) => '),
print_vdc( 7, 4 ).

View file

@ -0,0 +1,6 @@
% g(B,N,X):- consecutively generate in X the first N elements of the sequence based on {0, 1, ..., B}
g(_,N,[L|_]-_,X):- N > 1, atomic_list_concat(['0.'|L],X).
g(B,N,[L|Ls]-Xs,X):- N > 2, M is N-1, findall([I|L], between(0,B,I), T), append(T,Ys,Xs), g(B,M,Ls-Ys,X).
g(_,N,'0.0'):- N > 0.
g(B,N,X):- N > 0, findall([I], between(1,B,I), T), T \= [], append(T,Ys,Xs), g(B,N,Xs-Ys,X).

View file

@ -0,0 +1,20 @@
Procedure.d nBase(n.i,b.i)
Define r.d,s.i=1
While n
s*b
r+(Mod(n,b)/s)
n=Int(n/b)
Wend
ProcedureReturn r
EndProcedure
Define.i b,c
OpenConsole("van der Corput - Sequence")
For b=2 To 5
Print("Base "+Str(b)+": ")
For c=0 To 9
Print(StrD(nBase(c,b),5)+~"\t")
Next
PrintN("")
Next
Input()

View file

@ -0,0 +1,7 @@
def vdc(n, base=2):
vdc, denom = 0,1
while n:
denom *= base
n, remainder = divmod(n, base)
vdc += remainder / denom
return vdc

View file

@ -0,0 +1,5 @@
>>> [vdc(i) for i in range(10)]
[0, 0.5, 0.25, 0.75, 0.125, 0.625, 0.375, 0.875, 0.0625, 0.5625]
>>> [vdc(i, 3) for i in range(10)]
[0, 0.3333333333333333, 0.6666666666666666, 0.1111111111111111, 0.4444444444444444, 0.7777777777777777, 0.2222222222222222, 0.5555555555555556, 0.8888888888888888, 0.037037037037037035]
>>>

View file

@ -0,0 +1,4 @@
>>> from fractions import Fraction
>>> Fraction.__repr__ = lambda x: '%i/%i' % (x.numerator, x.denominator)
>>> [vdc(i, base=Fraction(2)) for i in range(10)]
[0, 1/2, 1/4, 3/4, 1/8, 5/8, 3/8, 7/8, 1/16, 9/16]

View file

@ -0,0 +1,12 @@
>>> for b in range(3,6):
print('\nBase', b)
print([vdc(i, base=Fraction(b)) for i in range(10)])
Base 3
[0, 1/3, 2/3, 1/9, 4/9, 7/9, 2/9, 5/9, 8/9, 1/27]
Base 4
[0, 1/4, 1/2, 3/4, 1/16, 5/16, 9/16, 13/16, 1/8, 3/8]
Base 5
[0, 1/5, 2/5, 3/5, 4/5, 1/25, 6/25, 11/25, 16/25, 21/25]

View file

@ -0,0 +1,26 @@
[ $ "bigrat.qky" loadfile ] now!
[ [] swap
[ dup while
base share /mod
rot join swap
again ]
drop ] is digits ( n --> [ )
[ base put
digits reverse
dup 0 swap
witheach
[ base share rot * + ]
base take rot size **
reduce ] is corput ( n n --> n/d )
5 times
[ say "base "
i^ 2 + dup echo
say ": "
10 times
[ i^ over corput
vulgar$ echo$ sp sp ]
cr drop ]

View file

@ -0,0 +1,16 @@
/*REXX program converts an integer (or a range) ──► a Van der Corput number in base 2.*/
numeric digits 1000 /*handle almost anything the user wants*/
parse arg a b . /*obtain the optional arguments from CL*/
if a=='' then parse value 0 10 with a b /*Not specified? Then use the defaults*/
if b=='' then b= a /*assume a range for a single number.*/
do j=a to b /*traipse through the range of numbers.*/
_= VdC( abs(j) ) /*convert absolute value of an integer.*/
leading= substr('-', 2 + sign(j) ) /*if needed, elide the leading sign. */
say leading || _ /*show number, with leading minus sign?*/
end /*j*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
VdC: procedure; y= x2b( d2x( arg(1) ) ) + 0 /*convert to hexadecimal, then binary.*/
if y==0 then return 0 /*handle the special case of zero. */
return '.'reverse(y) /*heavy lifting is performed by REXX. */

View file

@ -0,0 +1,52 @@
/*REXX pgm converts an integer (or a range) ──► a Van der Corput number, in base 2, or */
/*────────────────────────────── optionally, any other base up to and including base 90.*/
numeric digits 1000 /*handle almost anything the user wants*/
parse arg a b r . /*obtain optional arguments from the CL*/
if a=='' | a=="," then parse value 0 10 with a b /*Not specified? Then use the defaults*/
if b=='' | b=="," then b= a /* " " " " " " */
if r=='' | r=="," then r= 2 /* " " " " " " */
z= /*a placeholder for a list of numbers. */
do j=a to b /*traipse through the range of integers*/
_= VdC( abs(j), abs(r) ) /*convert the ABSolute value of integer*/
_= substr('-', 2 + sign(j) )_ /*if needed, keep the leading - sign.*/
if r>0 then say _ /*if positive base, then just show it. */
else z=z _ /* ··· else append (build) a list. */
end /*j*/
if z\=='' then say strip(z) /*if a list is wanted, then display it.*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
base: procedure; parse arg x, toB, inB /*get a number, toBase, and inBase. */
/*╔══════════════════════════════════════════════════════════════════════════════════╗
Input to this function: x (X is required and it must be an integer).
toBase the base to convert X to (default=10).
inBase the base X is expressed in (default=10).
toBase & inBase have a limit of: 2 90
*/
@abc= 'abcdefghijklmnopqrstuvwxyz' /*the lowercase Latin alphabet letters.*/
@abcU= @abc; upper @abcU /*go whole hog & extend with uppercase.*/
@@@= 0123456789 || @abc || @abcU /*prefix them with the decimal digits. */
@@@= @@@'<>[]{}()?~!@#$%^&*_+-=|\/;:`' /*add some special characters as well, */
/*──those chars should all be viewable.*/
numeric digits 1000 /*what the hey, support bigun' numbers.*/
maxB= length(@@@) /*maximum base (radix) supported here. */
if toB=='' then toB= 10 /*if omitted, then assume default (10)*/
if inB=='' then inB= 10 /* " " " " " " */
#=0 /* [↓] convert base inB X ──► base 10*/
do j=1 for length(x) /*process each "numeral" in the string.*/
_= substr(x, j, 1) /*pick off a "digit" (numeral) from X.*/
v= pos(_, @@@) /*get the value of this "digit"/numeral*/
if v==0 | v>inB then call erd /*is it an illegal "digit" (numeral) ? */
#= # * inB + v - 1 /*construct new number, digit by digit.*/
end /*j*/
y= /* [↓] convert base 10 # ──► base toB.*/
do while #>=toB /*deconstruct the new number (#). */
y= substr(@@@, # // toB + 1, 1)y /* construct the output number, ··· */
#= # % toB /* ··· and also whittle down #. */
end /*while*/
return substr(@@@, # + 1, 1)y /*return a constructed "numeric" string*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
erd: say 'the character ' v " isn't a legal numeral for base " inB'.'; exit 13
VdC: return '.'reverse( base( arg(1), arg(2) )) /*convert the #, reverse the #, append.*/

View file

@ -0,0 +1,7 @@
#lang racket
(define (van-der-Corput n base)
(if (zero? n)
0
(let-values ([(q r) (quotient/remainder n base)])
(/ (+ r (van-der-Corput q base))
base))))

View file

@ -0,0 +1,7 @@
#lang racket
(define (digit-length n base)
(if (< n base) 1 (add1 (digit-length (quotient n base) base))))
(define (digit n i base)
(remainder (quotient n (expt base i)) base))
(define (van-der-Corput n base)
(for/sum ([i (digit-length n base)]) (/ (digit n i base) (expt base (+ i 1)))))

View file

@ -0,0 +1,10 @@
(for ([base (in-range 2 (add1 5))])
(printf "Base ~a: " base)
(for ([n (in-range 0 10)])
(printf "~a " (van-der-Corput n base)))
(newline))
#| Base 2: 0 1/2 1/4 3/4 1/8 5/8 3/8 7/8 1/16 9/16
Base 3: 0 1/3 2/3 1/9 4/9 7/9 2/9 5/9 8/9 1/27
Base 4: 0 1/4 1/2 3/4 1/16 5/16 9/16 13/16 1/8 3/8
Base 5: 0 1/5 2/5 3/5 4/5 1/25 6/25 11/25 16/25 21/25 |#

View file

@ -0,0 +1,2 @@
constant VdC = map { :2("0." ~ .base(2).flip) }, ^Inf;
.say for VdC[^16];

View file

@ -0,0 +1,7 @@
sub VdC($base = 2) {
map {
[+] $_ && .polymod($base xx *) Z/ [\*] $base xx *
}, ^Inf
}
.say for VdC[^10];

View file

@ -0,0 +1,16 @@
sub vdc($num, $base = 2) {
my $n = $num;
my $vdc = 0;
my $denom = 1;
while $n {
$vdc += $n mod $base / ($denom *= $base);
$n div= $base;
}
$vdc;
}
for 2..5 -> $b {
say "Base $b";
say ( vdc($_,$b).Rat.nude.join('/') for ^10 ).join(', ');
say '';
}

View file

@ -0,0 +1,7 @@
sub vdc($value, $base = 2) {
my @values = $value, { $_ div $base } ... 0;
my @denoms = $base, { $_ * $base } ... *;
[+] do for (flat @values Z @denoms) -> $v, $d {
$v mod $base / $d;
}
}

View file

@ -0,0 +1,19 @@
decimals(4)
for base = 2 to 5
see "base " + string(base) + " : "
for number = 0 to 9
see "" + corput(number, base) + " "
next
see nl
next
func corput n, b
vdc = 0
denom = 1
while n
denom *= b
rem = n % b
n = floor(n/b)
vdc += rem / denom
end
return vdc

View file

@ -0,0 +1,8 @@
def vdc(n, base=2)
str = n.to_s(base).reverse
str.to_i(base).quo(base ** str.length)
end
(2..5).each do |base|
puts "Base #{base}: " + Array.new(10){|i| vdc(i,base)}.join(", ")
end

View file

@ -0,0 +1,24 @@
/// Van der Corput sequence for any base, based on C languange example from Wikipedia.
pub fn corput(nth: usize, base: usize) -> f64 {
let mut n = nth;
let mut q: f64 = 0.0;
let mut bk: f64 = 1.0 / (base as f64);
while n > 0_usize {
q += ((n % base) as f64)*bk;
n /= base;
bk /= base as f64;
}
q
}
fn main() {
for base in 2_usize..=5_usize {
print!("Base {}:", base);
for i in 1_usize..=10_usize {
let c = corput(i, base);
print!(" {:.6}", c)
}
println!("");
}
}

View file

@ -0,0 +1,12 @@
object VanDerCorput extends App {
def compute(n: Int, base: Int = 2) =
Iterator.from(0).
scanLeft(1)((a, _) => a * base).
map(b => (n - 1) / b -> b).
takeWhile(_._1 != 0).
foldLeft(0d)((a, b) => a + (b._1 % base).toDouble / b._2 / base)
val n = scala.io.StdIn.readInt
val b = scala.io.StdIn.readInt
(1 to n).foreach(x => println(compute(x, b)))
}

View file

@ -0,0 +1,32 @@
$ include "seed7_05.s7i";
include "float.s7i";
const func float: vdc (in var integer: number, in integer: base) is func
result
var float: vdc is 0.0;
local
var integer: denom is 1;
var integer: remainder is 0;
begin
while number <> 0 do
denom *:= base;
remainder := number rem base;
number := number div base;
vdc +:= flt(remainder) / flt(denom);
end while;
end func;
const proc: main is func
local
var integer: base is 0;
var integer: number is 0;
begin
for base range 2 to 5 do
writeln;
writeln("Base " <& base);
for number range 0 to 9 do
write(vdc(number, base) digits 6 <& " ");
end for;
writeln;
end for;
end func;

View file

@ -0,0 +1,15 @@
func vdc(value, base=2) {
while (value[-1] > 0) {
value.append(value[-1] / base -> int)
}
var (x, sum) = (1, 0)
value.each { |i|
sum += ((i % base) / (x *= base))
}
return sum
}
 
for base in (2..5) {
var seq = 10.of {|i| vdc([i], base) }
"base %d: %s\n".printf(base, seq.map{|n| "%.4f" % n}.join(', '))
}

View file

@ -0,0 +1,38 @@
mata
// 5th term of Van der Corput sequence
halton(1,1,5)
.625
// the first 10 terms of Van der Corput sequence
halton(10,1)
1
+---------+
1 | .5 |
2 | .25 |
3 | .75 |
4 | .125 |
5 | .625 |
6 | .375 |
7 | .875 |
8 | .0625 |
9 | .5625 |
10 | .3125 |
+---------+
// the first 10 terms of Van der Corput sequence in base 3
ghalton(10,3,0)
1
+---------------+
1 | .3333333333 |
2 | .6666666667 |
3 | .1111111111 |
4 | .4444444444 |
5 | .7777777778 |
6 | .2222222222 |
7 | .5555555556 |
8 | .8888888889 |
9 | .037037037 |
10 | .3703703704 |
+---------------+
end

View file

@ -0,0 +1,15 @@
clear
mata
st_addobs(2500)
st_addvar("double","x")
st_addvar("double","y")
st_addvar("double","z")
k=1::2500
st_store(k,1,k)
st_store(k,2,0.5*runiform(2500,1))
st_store(k,3,0.5:+0.5*halton(2500,1))
end
twoway scatter y x, msize(tiny) color(blue) ///
|| scatter z x, msize(tiny) color(green) legend(off) xtitle("") ///
title(Distribution: Van der Corput (top) vs pseudorandom) ///
ylabel(, angle(0) format(%3.1f))

View file

@ -0,0 +1,36 @@
func vanDerCorput(n: Int, base: Int, num: inout Int, denom: inout Int) {
var n = n, p = 0, q = 1
while n != 0 {
p = p * base + (n % base)
q *= base
n /= base
}
num = p
denom = q
while p != 0 {
n = p
p = q % p
q = n
}
num /= q
denom /= q
}
var num = 0
var denom = 0
for base in 2...5 {
print("base \(base): 0 ", terminator: "")
for n in 1..<10 {
vanDerCorput(n: n, base: base, num: &num, denom: &denom)
print("\(num)/\(denom) ", terminator: "")
}
print()
}

View file

@ -0,0 +1,10 @@
proc digitReverse {n {base 2}} {
set n [expr {[set neg [expr {$n < 0}]] ? -$n : $n}]
set result 0.0
set bit [expr {1.0 / $base}]
for {} {$n > 0} {set n [expr {$n / $base}]} {
set result [expr {$result + $bit * ($n % $base)}]
set bit [expr {$bit / $base}]
}
return [expr {$neg ? -$result : $result}]
}

View file

@ -0,0 +1,13 @@
# Print the first 10 terms of the Van der Corput sequence
for {set i 1} {$i <= 10} {incr i} {
puts "vanDerCorput($i) = [digitReverse $i]"
}
# In other bases
foreach base {3 4 5} {
set seq {}
for {set i 1} {$i <= 10} {incr i} {
lappend seq [format %.5f [digitReverse $i $base]]
}
puts "${base}: [join $seq {, }]"
}

View file

@ -0,0 +1,40 @@
fn v2(nn u32) f64 {
mut n:=nn
mut r := f64(0)
mut p := .5
for n > 0 {
if n&1 == 1 {
r += p
}
p *= .5
n >>= 1
}
return r
}
fn new_v(base u32) fn(u32) f64 {
invb := 1 / f64(base)
return fn[base,invb](nn u32) f64 {
mut n:=nn
mut r := f64(0)
mut p := invb
for n > 0 {
r += p * f64(n%base)
p *= invb
n /= base
}
return r
}
}
fn main() {
println("Base 2:")
for i := u32(0); i < 10; i++ {
println('$i ${v2(i)}')
}
println("Base 3:")
v3 := new_v(3)
for i := u32(0); i < 10; i++ {
println('$i ${v3(i)}')
}
}

View file

@ -0,0 +1,24 @@
Private Function vdc(ByVal n As Integer, BASE As Variant) As Variant
Dim res As String
Dim digit As Integer, g As Integer, denom As Integer
denom = 1
Do While n
denom = denom * BASE
digit = n Mod BASE
n = n \ BASE
res = res & CStr(digit) '+ "0"
Loop
vdc = IIf(Len(res) = 0, "0", "0." & res)
End Function
Public Sub show_vdc()
Dim v As Variant, j As Integer
For i = 2 To 5
Debug.Print "Base "; i; ": ";
For j = 0 To 9
v = vdc(j, i)
Debug.Print v; " ";
Next j
Debug.Print
Next i
End Sub

View file

@ -0,0 +1,48 @@
'http://rosettacode.org/wiki/Van_der_Corput_sequence
'Van der Corput Sequence fucntion call = VanVanDerCorput(number,base)
Base2 = "0" : Base3 = "0" : Base4 = "0" : Base5 = "0"
Base6 = "0" : Base7 = "0" : Base8 = "0" : Base9 = "0"
l = 1
h = 1
Do Until l = 9
'Set h to the value of l after each function call
'as it sets it to 0 - see lines 37 to 40.
Base2 = Base2 & ", " & VanDerCorput(h,2) : h = l
Base3 = Base3 & ", " & VanDerCorput(h,3) : h = l
Base4 = Base4 & ", " & VanDerCorput(h,4) : h = l
Base5 = Base5 & ", " & VanDerCorput(h,5) : h = l
Base6 = Base6 & ", " & VanDerCorput(h,6) : h = l
l = l + 1
Loop
WScript.Echo "Base 2: " & Base2
WScript.Echo "Base 3: " & Base3
WScript.Echo "Base 4: " & Base4
WScript.Echo "Base 5: " & Base5
WScript.Echo "Base 6: " & Base6
'Van der Corput Sequence
Function VanDerCorput(n,b)
k = RevString(Dec2BaseN(n,b))
For i = 1 To Len(k)
VanDerCorput = VanDerCorput + (CLng(Mid(k,i,1)) * b^-i)
Next
End Function
'Decimal to Base N Conversion
Function Dec2BaseN(q,c)
Dec2BaseN = ""
Do Until q = 0
Dec2BaseN = CStr(q Mod c) & Dec2BaseN
q = Int(q / c)
Loop
End Function
'Reverse String
Function RevString(s)
For j = Len(s) To 1 Step -1
RevString = RevString & Mid(s,j,1)
Next
End Function

View file

@ -0,0 +1,30 @@
Module Module1
Function ToBase(n As Integer, b As Integer) As String
Dim result = ""
If b < 2 Or b > 16 Then
Throw New ArgumentException("The base is out of range")
End If
Do
Dim remainder = n Mod b
result = "0123456789ABCDEF"(remainder) + result
n = n \ b
Loop While n > 0
Return result
End Function
Sub Main()
For b = 2 To 5
Console.WriteLine("Base = {0}", b)
For i = 0 To 12
Dim s = "." + ToBase(i, b)
Console.Write("{0,6} ", s)
Next
Console.WriteLine()
Console.WriteLine()
Next
End Sub
End Module

View file

@ -0,0 +1,31 @@
var v2 = Fn.new { |n|
var p = 0.5
var r = 0
while (n > 0) {
if (n%2 == 1) r = r + p
p = p / 2
n = (n/2).floor
}
return r
}
var newV = Fn.new { |base|
var invb = 1 / base
return Fn.new { |n|
var p = invb
var r = 0
while (n > 0) {
r = r + p*(n%base)
p = p * invb
n = (n/base).floor
}
return r
}
}
System.print("Base 2:")
for (i in 0..9) System.print("%(i) -> %(v2.call(i))")
System.print("\nBase 3:")
var v3 = newV.call(3)
for (i in 0..9) System.print("%(i) -> %(v3.call(i))")

View file

@ -0,0 +1,16 @@
include c:\cxpl\codes; \intrinsic 'code' declarations
func real VdC(N); \Return Nth term of van der Corput sequence in base 2
int N;
real V, U;
[V:= 0.0; U:= 0.5;
repeat N:= N/2;
if rem(0) then V:= V+U;
U:= U/2.0;
until N=0;
return V;
];
int N;
for N:= 0 to 10-1 do
[IntOut(0, N); RlOut(0, VdC(N)); CrLf(0)]

Some files were not shown because too many files have changed in this diff Show more