previndexinfo

code guessing, round #69, stage 2 (guessing)

started at ; stage 2 since . guess by

specification

congratulations, moja! this week we'll solve an equation in reverse. submissions can be written in any language.

RIES is a tool which takes any number and produces a list of equations which approximately solve to that number. it looks like this:

$ ries 69

   Your target value: T = 69.                                    mrob.com/ries

                    x/3 = e^pi                   for x = T + 0.422078    {62}
                    x-5 = 8^2                    ('exact' match)         {65}
                    x/7 = pi^2                   for x = T + 0.0872308   {61}
           1/sinpi(1/x) = 7 pi                   for x = T + 0.0634073   {78}
              sqrt(x-e) = 5+pi                   for x = T + 0.00381277  {80}
              sqrt(x)-9 = -ln(2)                 for x = T + 0.00380376  {81}
        sqrt(sqrt(x)+2) = ln(6)^2                for x = T + 0.00094879  {90}
              sqrt(x+3) = 6 sqrt(2)              for x = T + 2.84217e-14 {87}
  (Stopping now because best match is within 6.13e-14 of target value.)

  NOTE: 'exact' match may result from floating-point roundoff error.

  e = base of natural logarithms, 2.71828...  sinpi(X) = sin(pi * x)
  ln(x) = natural logarithm or log base e  sqrt(x) = square root
  pi = 3.14159...

                         --LHS--      --RHS--      -Total-
     max complexity:          51           44           95
          dead-ends:       43498        44320        87818  Time: 0.004
        expressions:        2286         2459         4745
           distinct:        1626         1432         3058  Memory: 228128 B

        Total equations tested:                 2328432 (2.328e+06)

we will be doing similar: finding equations that approximate a given number. note that this problem is inherently open-ended: any equation can be an approximation for any number, it just may be a very poor one. it is technically a valid solution to write a program that always returns 0, for instance, but it is not a very fun one.

your challenge, given a finite floating-point number, is to find 1 or more equations to which that number is a near-solution. as any language is allowed, there is no fixed API. best of-- good luck.

players

  1. chirk
  2. Dolphy
  3. essaie
  4. JJRubes
  5. kimapr
  6. LyricLy
  7. Makefile_dot_in
  8. Moja
  9. moshikoi
  10. oleander
  11. olus2000
  12. ponydork
  13. rebeca
  14. yeti
  15. yui

entries

you can download all the entries

entry #1

comments 0

post a comment


sixtynine.py ASCII text
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
from math import *

# security :D
x = eval(input("Target number: "))

print(f"x + 69 = {x + 69}")
print(f"x - 69 = {x - 69}")
print(f"x / 69 = {x / 69}")
print(f"x * 69 = {x * 69}")
print(f"x^69 = {x ** 69}")
print(f"x^(1 / 69) = {x ** (1 / 69)}")
if x != 0:
    print(f"69 / x = {69 / x}")
if x > 0:
    print(f"log_69(x) = {log(x, 69)}")

entry #2

comments 0

post a comment


main.c ASCII text
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/* Made by Linus Torvalds */
/* Pass an integer as the first argument to this program, or there will be consequences */
/* Consequences include: Terrible things */
/* I am writing these comments because I'm procrastinating */
/* You will not like the consequences */

#include <stdio.h>
#include <stdlib.h>

void PrintNumber(int num) {
	for (signed int i = 0; i < 32; ++ i) {
		if (num & (1 << i)) {
			printf("(1 << ");
			PrintNumber(i);
			printf(") + ");
		}
	}
	printf("0");
}

int main(int argc, char** argv) {
	puts("Seatbelt");
	int num = atoi(argv[1]);

	PrintNumber(num);
	puts("");
	return 4;
}
main.cal ASCII text
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# Made by Linus Torvalds
# Pass an integer as the first argument to this program, or there will be consequences
# Consequences include: Terrible things
# I am writing these comments because I'm procrastinating
# You will not like the consequences

include "cores/select.cal"
include "std/io.cal"
include "std/args.cal"
include "std/conv.cal"

func print_number cell num begin
	let cell i
	while i 32 < do
		if 1 i << num and then
			c"(1 << " print_str
			i print_number
			c") + " print_str
		end

		i ++ -> i
	end

	c"0" print_str
end

let Array arg
1 &arg get_arg &arg parse_int print_number new_line
main.d ASCII text
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// Made by Linus Torvalds
// Pass an integer as the first argument to this program, or there will be consequences
// Consequences include: Terrible things
// I am writing these comments because I'm procrastinating
// You will not like the consequences

import std.conv;
import std.stdio;

void PrintNumber(int num) {
	for (int i = 0; i < 32; ++ i) {
		if (num & (1 << i)) {
			write("(1 << ");
			PrintNumber(i);
			write(") + ");
		}
	}

	write("0");
}

void main(string[] args) {
	parse!int(args[1]).PrintNumber();
	writeln();
}
main.fs ASCII text
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
( FAILED ATTEMPT!!! Vorry )

: print_number ( num -- )
	0 do
		dup dup 1 swap lshift and if
			." (1 << "
			dup recurse
			." ) + "
		then
		1 + 
	dup 32 < while drop

	." 0"
;

52 print_number
main.nim ASCII text
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
# Made by Linus Torvalds
# Pass an integer as the first argument to this program, or there will be consequences
# Consequences include: Terrible things
# I am writing these comments because I'm procrastinating
# You will not like the consequences

import std/cmdline
import std/strutils
import std/strformat

proc PrintNumber*(num: int) =
    for i in 0 ..< 32:
        if (num and (1 shl i)) != 0:
            stdout.write("(1 << ")
            PrintNumber(i)
            stdout.write(") + ")
    stdout.write("0")


PrintNumber(parseInt(commandLineParams()[0]))
echo()
main.wpl ASCII text
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
# Made by Linus Torvalds
# WPL has no cmd parameters, so the value is hard coded in this program. Vorry :vob:

(printNumber = ([num] => {
	(i = 0) ;
	({i < 32} @ {
		((num & (1 << i)) ? {
			(stdout .s "(1 << ") ;
			(printNumber ! [i]) ;
			(stdout .s ") + ")
		}) ;
		(i = (i + 1))
	}) ;
	(stdout .s "0")
})) ;

(printNumber ! [52]) ;
(stdout .s "\n")
main.ysl ASCII text
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# Failed attempt, vorry

# Made by Linus Torvalds
# YSL has no cmd parameters, so the value is hard coded in this program. Vorry :vob:

goto *main

print_number:
	var num p
	var i = 0
	.loop:
		l_shift 1 $i
		var bitWith from return
		bit_and $num $bitWith
		var value from return
		cmp $value 0
		goto_if *.next
		print "(1 << "
		gosub *print_number $i
		print ") + "
	.next:
		var i += 1
		lt $i 32
		goto_if *.loop
		print "0"
		return

main:
	gosub *print_number 52
	println

entry #3

comments 0

post a comment


fries.factor ASCII text
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
! Copyright (C) 2025 Aleksander "olus2000" Sabak.
! See https://factorcode.org/license.txt for BSD license.
USING: combinators.short-circuit command-line.parser formatting
grouping.extras io kernel math math.floating-point math.parser
namespaces prettyprint sequences strings ;
IN: fries


<PRIVATE

: 1/ ( n -- 1/n ) 1 swap / ;

PRIVATE>


: >continued ( ratio -- continued )
  dup float? [ double>ratio ] when
  [ { } ] [ 1/ [ dup 0 = not ] [ 1/ 1 /mod swap ] produce nip ]
  if-zero ;


: continued> ( continued -- ratio )
  unclip-last-slice swap <reversed> [ [ 1/ ] dip + ] each ;


: approximations ( continued -- ratios )
  <prefixes> [ continued> ] map ;


: continued>string ( continued -- string )
  unclip-slice number>string swap
  [ "" [ "+1/(%d" sprintf append ] reduce ]
  [ length CHAR: ) <string> ] bi append append ;


: describe-approximation ( continued value -- description )
  [ [ continued>string ] [ continued> ] bi ] dip
  dupd - dup 0 > [ "+" ] [ "-" ] if swap abs
  "x = %s = %u for x = T %s %u" sprintf ;


: describe-approximations ( continued value -- descriptions )
  [ <prefixes> ] dip '[ _ describe-approximation ] map
  "\n" join ;


CONSTANT: full-description-template
"Your target value: T = %u

%s

NOTE: 'exact' match may result from floating-point roundoff error."


: full-description ( continued value -- description )
  tuck describe-approximations
  full-description-template sprintf ;


SYMBOLS: number-of-approximations approximation-target ;


: entry ( -- )
  { T{ option
       { name "--number" }
       { help "Up to how many approximations to print" }
       { type integer }
       { variable number-of-approximations }
       { default 5 }
       { validate [ { [ 0 > ] [ integer? ] } 1&& ] } }
    T{ option
       { name "target" }
       { help "Target number to approximate" }
       { type number }
       { variable approximation-target } } }
  [ approximation-target get dup >continued
    number-of-approximations get index-or-length head
    swap full-description print ] with-options ;


MAIN: entry

entry #4

comments 1
essaie

You might want to find a way to change those line terminators sometime ^^


post a comment


WarhammerButterscotch.js Unicode text, UTF-8 text, with CRLF line terminators
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
function findFactors(target) {
    const factors = [];
    for (let i = 1; i <= Math.sqrt(target); i++) {
        if (target % i === 0) {
            factors.push([i, target / i]);
        }
    }
    return factors;
}

console.log("Ƹ\\૮₍ ˶ᵔ ᵕ ᵔ˶ ₎ა/Ʒ -> Hiya! I'm Warhammer Butterscotch");

while (true) {
    let thing = +prompt("Enter your number, and I'll sprinkle some magic on it!: ");
    const original = thing;
    let equation = [];
    let last = "";

    console.log("*ੈ✩‧₊˚༺☆༻*ੈ✩‧₊˚");
    console.log(`   /)__/)
Ƹ\\( ˶• ༝ •˶)/Ʒ
o(   ⊃━☆*⛥*゚・。*.₊˚❀༉‧₊˚.`,thing);
    console.log("*ੈ✩‧₊˚༺☆༻*ੈ✩‧₊˚");

    for (let x = 0; x < 100; x++) {
        let choice = Math.floor(Math.random() * 10);

        switch (choice) {
            case 1:
                let value = thing - Math.floor(Math.random() * (thing - 0.1));
                if (value !== 0) {
                    equation.push(value, "+");
                    thing -= value;
                }
                break;
            case 2:
                if (equation.length > 1) {
                    let location = Math.floor(Math.random() * equation.length);
                    if (isNaN(equation[location])) location--;
                    
                    let factors = findFactors(equation[location]);
                    if (factors.length > 1) {
                        let [a, b] = factors[Math.floor(Math.random() * (factors.length - 1)) + 1];
                        equation.splice(location, 1, "(", a, "*", b, ")");
                    }
                }
                break;
        }

        let currentEquation = equation.join("") + thing + "=" + original;
        if (currentEquation !== last) {
            console.log("Ƹ\\૮₍ ˶ᵔ ᵕ ᵔ˶ ₎ა/Ʒ 。*.₊ " + currentEquation);
        }
        last = currentEquation;
    }

    console.log("*ੈ✩‧₊˚༺☆༻*ੈ✩‧₊˚");
    console.log("Hiya, your equation is done! Ƹ\\૮₍ ˃ ⤙ ˂ ₎ა/Ʒ Hope you like it!");
    console.log(equation.join("") + thing + "=" + original);
    console.log("Go again? Ƹ\\૮₍´˶• . • ⑅ ₎ა/Ʒ");

    let retry = prompt("(Y/N) => ").toLowerCase();
    if (retry === "n" || retry === "no") break;
}

entry #5

comments 0

post a comment


entry.c ASCII text
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <stdlib.h>
#include <stdio.h>
#include <math.h>

#define d double
#define ESTIMATE(O, N) ((O) - (N)) * SIX + (N) * (PI + E)

d SIX = 6.00000000000000000000000000000000000000000000000000000000000000000000;
d PI  = 3.14159265358979323846264338327950288419716939937510582097494459230781;
d E   = 2.71828182845904523536028747135266249775724709369995957496696762772407;

int main(int argc, char** argv) {
    if(argc != 2) {
        printf("Please provide one target number.\n");
        return -1;
    }

    d target = strtod(argv[1], NULL);

    if(fmod(target, SIX) == 0) {
        printf("%f * 6 = %f\n", target / SIX, target);
        return 0;
    }

    /*          M E T A S T A C K          */
    d n = 0;
    d overestimate = ceil(target / SIX);
    while(ESTIMATE(overestimate, n) > target) {
        n++;
    }

    d above = ESTIMATE(overestimate, n - 1);
    d below = ESTIMATE(overestimate, n);
    if(target - below < above - target) {
        printf("%f * 6 + %f * (pi + e) = %f\n", overestimate - n, n, below);
        return 0;
    }

    printf("%f * 6 + %f * (pi + e) = %f\n", overestimate - n - 1, n - 1, below);
    return 0;
}

entry #6

comments 0

post a comment


nice.fasm ASCII text
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
format ELF64 executable
macro prn [msg] {
	local .d
	jmp @f
	.d: db msg
	@@: mov rdx, $ - .d
		mov rsi, .d
		mov rax, 1
		mov rdi, 1
		syscall
} prn "Number: "
mov rax, 0
mov rdi, 0
mov rsi, rsp
mov rdx, 10
syscall
mov rdi, rsp
mov rax, 0
mov rcx, 10
.L: xor rbx, rbx
	mov bl, byte [rdi]
	inc rdi
	cmp rbx, 10
	je .E
	sub rbx, 48
	cmp rbx, 10
	jnae .I
	prn "Invalid number", 10
	jmp .X
	.I: mul rcx
	add rax, rbx
	jmp .L
.E: xor rdx, rdx
mov rbx, 2
div rbx
mov r15, rax
add r15, rdx
xor rdx, rdx
mov rbx, 2
div rbx
call print
prn "*2+"
mov rax, r15
call print
prn 10
.X: mov rax, 60
mov rdi, 0
syscall
print:
	mov rbx, 1
	mov rsi, 10
	dec rsp
	mov qword [rsp-8], 0
	mov qword [rsp-16], 0
	.L: xor rdx, rdx
		div rsi
		add dl, 48
		mov byte [rsp], dl
		inc rbx
		dec rsp
		test rax, rax
		jnz .L
	mov rdx, rbx
	mov rsi, rsp
	mov rax, 1
	mov rdi, 1
	syscall
	add rsp, rbx
	ret

entry #7

comments 0

post a comment


entry.scm ASCII text
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
; step 1
(import (rename (rnrs(6)) (lambda h)(define s)
                          (begin z)(set! q)))

; step 2
(s entry(let*((g call-with-string-output-port)(j abs)(c expt)(p(h(b)(s i
0)(h()(q i(+ 1 i))(/ b(c 2(- i 1))))))(k log)(d(h(x)(c 2(exact(ceiling(/
(k(let((x(j x)))(if(= x 0)1 x)))(k 2)))))))(m display)(w write))(h(x)(
let((b(p(d x)))(y 0))(g(h(o)(m"x = "o)(do((n(b)(b))(i 0(+ 1 i)))((or(= y
x)(> i 1000)(<(j(let((f(j x)))(-(/ y f)(/ x f))))#e1e-9)))(let*((a(+ y n
))(b(- y n))(u(j(- x a)))(v(j(- x b))))(if(< u v)(z(q y a)(m(if(= i 0)""
" + ")o)(w n o))(z(q y b)(m(if(= i 0)"-"" - ")o)(w n o)))))(if(= y 0)(m
0 o)0)))))))

; step 3
(s(main args)(apply(h(_ x)(display(entry(string->number x)))
(display "\n"))args))(main (command-line))

entry #8

comments 0

post a comment


better_ries.py ASCII text
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
import sys

x = eval(sys.argv[1]) # safe

import math
s = ("%+f" % math.copysign(1, x))[0]
i = "1e50085" # "le boobs"
y = "x = %c %%s"

if math.isnan(x):
    y = y % s % "%s / %%s" % i % i

elif not math.isfinite(x):
    y = y % s % "%s" % i

elif abs(x) == 0:
    y = y % s % "%s / %%s" % 0.0 % i

else:
    y = y % s % "%s / %%%%s" % "(%%%%%%%%s * %s)" % i % "(%%s * %s)" % i % abs(x).as_integer_ratio()

print(y)

entry #9

comments 0

post a comment


cg69.el Unicode text, UTF-8 text
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
(defun shitty-ries (n)
  (interactive "nThose who know: ")
  (with-temp-buffer
    (rename-buffer "Knowledge")
    (print `(= (- x ,n) 0) (current-buffer))
    (print `(= (- x (/ π ,(/ float-pi n))) 0) (current-buffer))
    (dotimes (i 10)
      (let ((r (+ n (random 0.01))) ; for increased fun
            (a (random))
            (y (random)))
        (print `(= (+ (* ,a (^ x 2)) (* ,(- (+ y r)) x) ,(* y r)) 0) (current-buffer))))
    (print-buffer)))
        
    

entry #10

comments 0

post a comment


RushE.hs Unicode text, UTF-8 text
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import Control.Applicative
import Control.Monad
import System.Environment

data Expr = E | Plus Expr Expr | Times Expr Expr | Minus Expr Expr | Over Expr Expr | ToThe Expr Expr | Log Expr Expr | ThRoot Expr Expr

instance Show Expr where
   showsPrec prec x = let
     (s, pred) = case x of
       E -> (('e':), 11)
       Log x y -> (("log_"++) . showsPrec 11 x . ('(':) . showsPrec 0 y . (')':), 11)
       ToThe x y -> (showsPrec 9 x . ('^':) . showsPrec 8 y, 8)
       ThRoot x y -> (showsPrec 9 x . ('√':) . showsPrec 8 y, 8)
       Times x y -> (showsPrec 6 x . ('*':) . showsPrec 6 y, 6)
       Over x y -> (showsPrec 6 x . ('/':) . showsPrec 7 y, 6)
       Plus x y -> (showsPrec 4 x . ('+':) . showsPrec 4 y, 4)
       Minus x y -> (showsPrec 4 x . ('-':) . showsPrec 5 y, 4)
      in if pred < prec then ('(':) . s . (')':) else s

far :: RealFloat a => a -> a -> Bool
far x y = abs (x - y) > 1e-9 * max (abs x) (abs y)

allAt :: RealFloat a => Int -> [(Expr, a)]
allAt 0 = [(E, exp 1)]
allAt n = do
  (x, a) <- allAt (n-1)
  do
    (y, b) <- allAt (n-1)
    (z, c) <- pure (Plus x y, a + b)
      <|> pure (Times x y, a * b)
      <|> (Minus x y, a - b) <$ guard (far a b)
      <|> (Over x y, a / b) <$ guard (far a b)
      <|> pure (ToThe x y, a ** b)
      <|> (Log x y, logBase a b) <$ guard (far a b)
      <|> pure (ThRoot x y, b ** recip a)
    guard $ not (isNaN c)
    pure (z, c)

allOfThem :: RealFloat a => [(Expr, a)]
allOfThem = [0..] >>= allAt

stalinSortBy :: Ord b => (a -> b) -> [a] -> [a]
stalinSortBy _ [] = []
stalinSortBy f (x:xs) = x : go (f x) xs
  where
    go _ [] = []
    go worst (x:xs)
      | fitness >= worst = go worst xs
      | otherwise = x : go fitness xs
      where fitness = f x

fitness :: RealFloat a => a -> a -> a
fitness target x
  | far target x = abs (target - x)
  | otherwise = 1 / 0

hone :: (Ord a, RealFloat a) => a -> [(Expr, a)]
hone n = stalinSortBy (fitness n . snd) $ allOfThem

main :: IO ()
main = getArgs >>= putStrLn . unlines . map show . hone . read . head

entry #11

comments 0

post a comment


ries.awk ASCII text
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#!/usr/bin/awk -f

BEGIN {
    print "to use really incredible equation sleuthe"
    print "dot awk working komputer please type ries"
    print "followed by number you will investigating"
}

$1 == "ries" {
    x = $2
    s = x < 0 ? -1 : 1
    w = int(s * x)
    f = s * x - w
    print "x = "s" * ("w" + "ra(f, 0, 1, 1, 1)")"
}

function ra(f, a, b, c, d,   C, N, D) {
    N = a + c
    D = b + d
    if (C > 1000)
        return N"/"D
    else if (f < N / D)
        return ra(f, a, b, N, D, C + 1)
    else if (f > N / D)
        return ra(f, N, D, c, d, C + 1)
    else
        return N"/"D
}

entry #12

comments 0

post a comment


cg69.lua ASCII text
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
#!/usr/bin/env luajit
local target = assert(tonumber((...)),'Need target value!')

local consts = {
	{'pi',math.pi},
	{'e',math.exp(1)},
	{'phi',(math.sqrt(5)+1)/2},
	{'1/2',1/2}}
for i = 1,9 do table.insert(consts, {tostring(i),i}) end

local unary = {
	{'ln',math.log,inv='exp'},
	{'exp',math.exp,inv='ln'},
	{'sqrt',math.sqrt,inv='sqr'},
	{'sqr',function(x)return x^2 end,inv='sqrt'},
	{'sinpi',function(x)return math.sin(math.pi*x)end,noint=true},
	{'cospi',function(x)return math.cos(math.pi*x)end,noint=true},
	{'tanpi',function(x)return math.tan(math.pi*x)end,noint=true},
	{'sin',math.sin},
	{'cos',math.cos},
	{'tan',math.tan},
	{'-',function(x)return -x end,inv='-'},
	{'1/',function(x)return 1/x end,inv='1/'}}

local binary = {
	{'logab',math.log,norat=true},
	{'atan2',math.atan2,norat=true},
	-- {'root',function(a,b)return b^(1/a) end,norat=true},
	{'+',function(a,b) return a+b end,comm=true},
	{'*',function(a,b) return a*b end,comm=true},
	{'^',function(a,b) return a^b end},
	{'-',function(a,b) return a-b end,norat=true},
	{'/',function(a,b) return a/b end,norat=true}}

local rhs = {}
for _,const in ipairs(consts) do table.insert(rhs,{val=const[2],str=const[1],is='c',c=1,side='r'}) end
local lhs = {{val=target,str='x',is='x',c=1,side='l'}}

local C = 1

local function dist(a,b) return math.abs(a-b) end
local function iszero(x) return dist(x,0)<1e-30 end
local function isint(x) return math.min(dist(x,math.floor(x)),dist(x,math.ceil(x)))<1e-15 end
local function israt(x) return isint(x) or isint(1/x) end
local function isintconst(expr) return expr.is=='c' and isint(expr.val) end

local function form1(expr,op)
	local opn,v=op[1],expr.val
	local nc = 1+expr.c if nc ~= C then return end
	if op.noint and isint(expr.val) then return end
	if op.inv == expr.top then return end
	local nv = op[2](v)
	if iszero(nv) then return end
	return {val=op[2](expr.val),str=op[1]..'('..expr.str..')',c=nc,side=expr.side,top=opn} end

local function form2(expr,expr2,op)
	local opn,v,v2=op[1],expr.val,expr2.val
	local nc = 1+expr.c+expr2.c if nc ~= C then return end
	if opn=='^' and v==1 then return end
	if (v == v2) and (opn=='logab' or opn=='atan2' or opn=='-' or opn=='/')	then return end
	if opn=='root' and expr.is=='x' then return end
	if op.norat and israt(v/v2) then return end
	local nv = op[2](v,v2) if iszero(nv) or (opn=='logab' and israt(nv)) then return end

	return {val=nv,c=nc,side=expr.side,
		str=#opn==1 and '('..expr.str..')'..opn..'('..expr2.str..')'
		              or opn..'('..expr.str..','..expr2.str..')'} end

local function cinsert(list,expr)
	if expr then local x = expr.val if x==x and x~=x+1 then
		table.insert(list,expr) end end end

local function nextstep(exprlist)
	local n = #exprlist
	for ix=1,n do 
		local expr=exprlist[ix]
		for _,op in ipairs(unary) do
			cinsert(exprlist,form1(expr,op))end
		for ix2=1,n do local expr2=exprlist[ix2]
			for _,op in ipairs(binary) do if ix<=ix2 or not op.comm then
			cinsert(exprlist,form2(expr,expr2,op))end end end end end

local function put(lx,rx,d)
	local s = ('%s {%d} = {%d} %s'):format(lx.str,lx.c,rx.c,rx.str)
	local function sp(n) return (' '):rep(n) end
	local sx = sp(30-#lx.str)..s
	local sd = ('d = %.2e'):format(d)
	print(sx..sp(70-#sx)..sd) end

local threshold=0.0001
for c=1,6 do
	C = c  nextstep(lhs) nextstep(rhs)
	local all = {}
	table.move(lhs,1,#lhs,1,all) table.move(rhs,1,#rhs,#lhs+1,all)
	table.sort(all,function(a,b) return a.val<b.val end)
	for i=1,#all-1 do local ex,ex2=all[i],all[i+1] local d=math.abs(ex.val-ex2.val)
		if ex.side ~= ex2.side and d < threshold then
			if d>0 then threshold=d end
			if ex.side=='l' then put(ex,ex2,d) else put(ex2,ex,d) end
			if 0<d and d<1e-15 then goto done end end end end ::done::

entry #13

comments 0

post a comment


cg.py ASCII text, with CRLF line terminators
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
from math import pi, e, sqrt
import sys

max_float = sys.float_info.max
phi = (1. + sqrt(5))/2

ops = [
    (lambda x,y:x+y, "+", lambda x,y: True),
    (lambda x,y:x-y, "-", lambda x,y: True),
    (lambda x,y:x*y, "*", lambda x,y: True),
    (lambda x,y:x/y, "/", lambda x,y: y!=0.),
    (lambda x,y:x**y, "^", lambda x,y: x>0. and (y <= 1. or x <= max_float**(1/y))),
]

consts = [
    (1., "1"),
    (pi, "pi"),
    (e, "e"),
    (phi, "phi"),
]

num_symbols = len(ops)+len(consts)

def decode_op(number):
    global ops, num_symbols
    num_consts = len(consts)
    assert number%num_symbols >= num_consts
    (op, sop, cond) = ops[number%num_symbols-num_consts]
    return (op, sop, cond, number//num_symbols)

def decode_expr(number):
    global num_symbols, consts
    digit=number%num_symbols
    if digit < len(consts):
        (value, strep)=consts[digit]
        return (value, strep, number//num_symbols)
    (op, sop, cond, number)=decode_op(number)
    (l, sl, number)=decode_expr(number)
    if l is None:
        return (None, None, number)
    (r, sr, number)=decode_expr(number)
    if r is None or not cond(l, r): 
        return (None, None, number)
    return (op(l, r), f"{sl} {sr} {sop}", number)

inp = float(input("Enter number: "))
best_diff = float("inf")
current = 0

while best_diff > 0.:
    (number, strep, _) = decode_expr(current)
    if number is None:
        current += 1
        continue
    diff = abs(inp-number)
    if diff < best_diff:
        print(f"{strep} = {number}, (difference = {diff})")
        best_diff = diff
    current += 1

entry #14

comments 0

post a comment


main.cpp Unicode text, UTF-8 text
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
	double iterations = 10000;
    cout << "Enter a positive value:" << endl;
	double target;
	double result;
	cin >> target;
	cout << "Target value: " << target << endl << endl;
	
	double final_a = 0;
	double final_b = 1;
	double final_result = 1.0;
	
	for (int a = 0; a < iterations; a++) {
		for (int b = 1; b < iterations; b++) {
			double result = exp(a) / b;
			if (abs(target - result) < abs(target - final_result)) {
				final_a = a;
				final_b = b;
				final_result = result;
			}
		}
	}

	cout << "e^" << final_a << "/" << final_b << "=" << final_result << endl;
	cout << abs(target - final_result) << " from target value" << endl << endl;
	
	
	final_a = 1;
	final_b = 1;
	final_result = M_PI;
	
	for (int a = 1; a < iterations; a++) {
		for (int b = 1; b < iterations; b++) {
			double result = a * M_PI / b;
			if (abs(target - result) < abs(target - final_result)) {
				final_a = a;
				final_b = b;
				final_result = result;
			}
		}
	}

	cout << final_a << "π/" << final_b << "=" << final_result << endl;
	cout << abs(target - final_result) << " from target value" << endl <<endl;

}

entry #15

comments 0

post a comment


names.py ASCII text, with CRLF line terminators
1
print(input()) # gold star