Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

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

View file

@ -0,0 +1,25 @@
The TPK algorithm is an early example of a programming chrestomathy.
It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report [http://bitsavers.org/pdf/stanford/cs_techReports/STAN-CS-76-562_EarlyDevelPgmgLang_Aug76.pdf The Early Development of Programming Languages].
The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of the algorithm.
From the [[wp:Trabb PardoKnuth algorithm|wikipedia entry]]:
'''ask''' for 11 numbers to be read into a sequence ''S''
'''reverse''' sequence ''S''
'''for each''' ''item'' '''in''' sequence ''S''
''result'' ''':=''' '''call''' a function to do an ''operation''
'''if''' ''result'' overflows
'''alert''' user
'''else'''
'''print''' ''result''
The task is to implement the algorithm:
# Use the function: &nbsp; &nbsp; <big><math>f(x) = |x|^{0.5} + 5x^3</math></big>
# The overflow condition is an answer of greater than 400.
# The 'user alert' should not stop processing of other items of the sequence.
# Print a prompt before accepting '''eleven''', textual, numeric inputs.
# You may optionally print the item as well as its associated result, but the results must be in reverse order of input.
# The sequence &nbsp; ''' ''S'' ''' &nbsp; may be 'implied' and so not shown explicitly.
# ''Print and show the program in action from a typical run here''. (If the output is graphical rather than text then either add a screendump or describe textually what is displayed).
<br><br>

View file

@ -0,0 +1,12 @@
F f(x)
R sqrt(abs(x)) + 5 * x ^ 3
V s = Array(1..11)
s.reverse()
L(x) s
V result = f(x)
I result > 400
print(#.: #..format(x, TOO LARGE!))
E
print(#.: #..format(x, result))
print()

View file

@ -0,0 +1,13 @@
begin
integer i; real y; real array a[0:10];
real procedure f(t); value t; real t;
f:=sqrt(abs(t))+5*t^3;
for i:=0 step 1 until 10 do inreal(0, a[i]);
for i:=10 step -1 until 0 do
begin
y:=f(a[i]);
if y > 400 then outstring(1, "TOO LARGE")
else outreal(1,y);
outchar(1, "\n", 1)
end
end

View file

@ -0,0 +1,10 @@
[ 0 : 10 ]REAL a;
PROC f = ( REAL t )REAL:
sqrt(ABS t)+5*t*t*t;
FOR i FROM LWB a TO UPB a DO read( ( a[ i ] ) ) OD;
FOR i FROM UPB a BY -1 TO LWB a DO
REAL y=f(a[i]);
IF y > 400 THEN print( ( "TOO LARGE", newline ) )
ELSE print( ( fixed( y, -9, 4 ), newline ) )
FI
OD

View file

@ -0,0 +1,13 @@
begin
real y; real array a( 0 :: 10 );
real procedure f( real value t );
sqrt(abs(t))+5*t*t*t;
for i:=0 until 10 do read( a(i) );
r_format := "A"; r_w := 9; r_d := 4;
for i:=10 step -1 until 0 do
begin
y:=f(a(i));
if y > 400 then write( "TOO LARGE" )
else write( y );
end
end.

View file

@ -0,0 +1,11 @@
{res}Trabb;f;S;i;a;y ⍝ define a function Trabb
f{(0.5*|)+5×*3} ⍝ define a function f
S,{ ()}'Please, enter 11 numbers: '
:For i a :InEach (S)(S) ⍝ loop through N..1 and reversed S
:If 400<yf(a)
'Too large: ',i
:Else
i,y
:EndIf
:EndFor

View file

@ -0,0 +1,78 @@
REM Trabb Pardo-Knuth algorithm
REM Used "magic numbers" because of strict specification of the algorithm.
DIM S@(10)
PRINT "Enter 11 numbers."
FOR I = 0 TO 10
I1= I + 1
PRINT I1;
PRINT " => ";
INPUT TMP@
S@(I) = TMP@
NEXT I
PRINT
REM Reverse
HALFIMAX = 10 / 2
FOR I = 0 TO HALFIMAX
IREV = 10 - I
TMP@ = S@(I)
S@(I) = S@(IREV)
S@(IREV) = TMP@
NEXT I
REM Results
REM Leading spaces in printed numbers are removed
CLS
FOR I = 0 TO 10
PRINT "f(";
STMP$ = STR$(S@(I))
STMP$ = LTRIM$(STMP$)
PRINT STMP$;
PRINT ") = ";
N@ = S@(I)
GOSUB CALCF:
R@ = F@
IF R@ > 400 THEN
PRINT "overflow"
ELSE
STMP$ = STR$(R@)
STMP$ = LTRIM$(STMP$)
PRINT STMP$
ENDIF
NEXT I
END
CALCF:
REM Calculates f(N@)
REM Result in F@
X@ = ABS(N@)
GOSUB CALCSQRT:
F@ = 5.0 * N@
F@ = F@ * N@
F@ = F@ * N@
F@ = F@ + SQRT@
RETURN
CALCSQRT:
REM Calculates approximate (+- 0.00001) square root of X@ for X@ >= 0 (bisection method)
REM Result in SQRT@
A@ = 0.0
IF X@ >= 1.0 THEN
B@ = X@
ELSE
B@ = 1.0
ENDIF
L@ = B@ - A@
L@ = ABS(L@)
WHILE L@ > 0.00001
MIDDLE@ = A@ + B@
MIDDLE@ = MIDDLE@ / 2
MIDDLETO2@ = MIDDLE@ * MIDDLE@
IF MIDDLETO2@ < X@ THEN
A@ = MIDDLE@
ELSE
B@ = MIDDLE@
ENDIF
L@ = B@ - A@
L@ = ABS(L@)
WEND
SQRT@ = MIDDLE@
RETURN

View file

@ -0,0 +1,17 @@
# syntax: GAWK -f TRABB_PARDO-KNUTH_ALGORITHM.AWK
BEGIN {
printf("enter 11 numbers: ")
getline S
n = split(S,arr," ")
if (n != 11) {
printf("%d numbers entered; S/B 11\n",n)
exit(1)
}
for (i=n; i>0; i--) {
x = f(arr[i])
printf("f(%s) = %s\n",arr[i],(x>400) ? "too large" : x)
}
exit(0)
}
function abs(x) { if (x >= 0) { return x } else { return -x } }
function f(x) { return sqrt(abs(x)) + 5 * x ^ 3 }

View file

@ -0,0 +1,36 @@
with Ada.Text_IO, Ada.Numerics.Generic_Elementary_Functions;
procedure Trabb_Pardo_Knuth is
type Real is digits 6 range -400.0 .. 400.0;
package TIO renames Ada.Text_IO;
package FIO is new TIO.Float_IO(Real);
package Math is new Ada.Numerics.Generic_Elementary_Functions(Real);
function F(X: Real) return Real is
begin
return (Math.Sqrt(abs(X)) + 5.0 * X**3);
end F;
Values: array(1 .. 11) of Real;
begin
TIO.Put("Please enter 11 Numbers:");
for I in Values'Range loop
FIO.Get(Values(I));
end loop;
for I in reverse Values'Range loop
TIO.Put("f(");
FIO.Put(Values(I), Fore => 2, Aft => 3, Exp => 0);
TIO.Put(")=");
begin
FIO.Put(F(Values(I)), Fore=> 4, Aft => 3, Exp => 0);
exception
when Constraint_Error => TIO.Put("-->too large<--");
end;
TIO.New_Line;
end loop;
end Trabb_Pardo_Knuth;

View file

@ -0,0 +1,13 @@
scope # TPK algorithm in Agena
local y;
local a := [];
local f := proc( t :: number ) is return sqrt(abs(t))+5*t*t*t end;
for i from 0 to 10 do a[i] := tonumber( io.read() ) od;
for i from 10 to 0 by - 1 do
y:=f(a[i]);
if y > 400
then print( "TOO LARGE" )
else printf( "%10.4f\n", y )
fi
od
epocs

View file

@ -0,0 +1,18 @@
10 REM Trabb Pardo-Knuth algorithm
20 HOME : REM 20 CLS for Chipmunk Basic or GW-BASIC
30 DIM S(10)
40 PRINT "Enter 11 numbers."
50 FOR I = 0 TO 10
60 PRINT I+1;
70 INPUT "=> ";S(I)
80 NEXT I
90 PRINT
100 REM Results
110 FOR I = 10 TO 0 STEP -1
120 PRINT "f( " S(I)") = ";
130 F = S(I)
140 R = SQR(ABS(F))+5*F^3
150 IF R > 400 THEN PRINT "-=< overflow >=-"
160 IF R <= 400 THEN PRINT R
170 NEXT I
180 END

View file

@ -0,0 +1,11 @@
proc: function [x]->
((abs x) ^ 0.5) + 5 * x ^ 3
ask: function [msg][
to [:floating] first.n: 11 split.words strip input msg
]
loop reverse ask "11 numbers: " 'n [
result: proc n
print [n ":" (result > 400)? -> "TOO LARGE!" -> result]
]

View file

@ -0,0 +1,17 @@
seq := [1,2,3,4,5,6,7,8,9,10,11]
MsgBox % result := TPK(seq, 400)
return
TPK(s, num){
for i, v in reverse(s)
res .= v . " : " . ((x:=f(v)) > num ? "OVERFLOW" : x ) . "`n"
return res
}
reverse(s){
Loop % s.Count()
s.InsertAt(A_Index, s.pop())
return s
}
f(x){
return Sqrt(x) + 5* (x**3)
}

View file

@ -0,0 +1,24 @@
; Trabb PardoKnuth algorithm
; by James1337 (autoit.de)
; AutoIt Version: 3.3.8.1
Local $S, $i, $y
Do
$S = InputBox("Trabb PardoKnuth algorithm", "Please enter 11 numbers:", "1 2 3 4 5 6 7 8 9 10 11")
If @error Then Exit
$S = StringSplit($S, " ")
Until ($S[0] = 11)
For $i = 11 To 1 Step -1
$y = f($S[$i])
If ($y > 400) Then
ConsoleWrite("f(" & $S[$i] & ") = Overflow!" & @CRLF)
Else
ConsoleWrite("f(" & $S[$i] & ") = " & $y & @CRLF)
EndIf
Next
Func f($x)
Return Sqrt(Abs($x)) + 5*$x^3
EndFunc

View file

@ -0,0 +1,20 @@
dim s(11)
print 'enter 11 numbers'
for i = 0 to 10
input i + ">" , s[i]
next i
for i = 10 to 0 step -1
print "f(" + s[i] + ")=";
x = f(s[i])
if x > 400 then
print "-=< overflow >=-"
else
print x
endif
next i
end
function f(n)
return sqrt(abs(n))+5*n^3
end function

View file

@ -0,0 +1,24 @@
#include <iostream>
#include <cmath>
#include <vector>
#include <algorithm>
#include <iomanip>
int main( ) {
std::vector<double> input( 11 ) , results( 11 ) ;
std::cout << "Please enter 11 numbers!\n" ;
for ( int i = 0 ; i < input.size( ) ; i++ )
std::cin >> input[i];
std::transform( input.begin( ) , input.end( ) , results.begin( ) ,
[ ]( double n )-> double { return sqrt( abs( n ) ) + 5 * pow( n , 3 ) ; } ) ;
for ( int i = 10 ; i > -1 ; i-- ) {
std::cout << "f( " << std::setw( 3 ) << input[ i ] << " ) : " ;
if ( results[ i ] > 400 )
std::cout << "too large!" ;
else
std::cout << results[ i ] << " !" ;
std::cout << std::endl ;
}
return 0 ;
}

View file

@ -0,0 +1,37 @@
#include<math.h>
#include<stdio.h>
int
main ()
{
double inputs[11], check = 400, result;
int i;
printf ("\nPlease enter 11 numbers :");
for (i = 0; i < 11; i++)
{
scanf ("%lf", &inputs[i]);
}
printf ("\n\n\nEvaluating f(x) = |x|^0.5 + 5x^3 for the given inputs :");
for (i = 10; i >= 0; i--)
{
result = sqrt (fabs (inputs[i])) + 5 * pow (inputs[i], 3);
printf ("\nf(%lf) = ");
if (result > check)
{
printf ("Overflow!");
}
else
{
printf ("%lf", result);
}
}
return 0;
}

View file

@ -0,0 +1,23 @@
10 rem Trabb Pardo-Knuth algorithm
20 cls
30 dim s(10)
40 print "Enter 11 numbers."
50 for i = 0 to 10
60 print i+1;
70 input "=> ";s(i)
80 next i
90 print
160 'Results
170 for i = 10 to 0 step -1
180 print "f( " s(i)") = ";
190 r = f(s(i))
200 if r > 400 then
210 print "-=< overflow >=-"
220 else
230 print r
240 endif
250 next i
260 end
270 function f(n)
280 f = sqr(abs(n))+5*n^3
290 return

View file

@ -0,0 +1,23 @@
10 REM TRABB PARDO-KNUTH ALGORITHM
20 REM USED "MAGIC NUMBERS" BECAUSE OF STRICT SPECIFICATION OF THE ALGORITHM.
30 DEF FNF(N)=SQR(ABS(N))+5*N*N*N
40 DIM S(10)
50 PRINT "ENTER 11 NUMBERS."
60 FOR I=0 TO 10
70 PRINT STR$(I+1);
80 INPUT S(I)
90 NEXT I
100 PRINT
110 REM REVERSE
120 FOR I=0 TO 10/2
130 TMP=S(I)
140 S(I)=S(10-I)
150 S(10-I)=TMP
160 NEXT I
170 REM RESULTS
180 FOR I=0 TO 10
190 PRINT "F(";STR$(S(I));") =";
200 R=FNF(S(I))
210 IF R>400 THEN PRINT " OVERFLOW":ELSE PRINT R
220 NEXT I
230 END

View file

@ -0,0 +1,13 @@
(defun read-numbers ()
(princ "Enter 11 numbers (space-separated): ")
(let ((numbers '()))
(dotimes (i 11 numbers)
(push (read) numbers))))
(defun trabb-pardo-knuth (func overflowp)
(let ((S (read-numbers)))
(format T "~{~a~%~}"
(substitute-if "Overflow!" overflowp (mapcar func S)))))
(trabb-pardo-knuth (lambda (x) (+ (expt (abs x) 0.5) (* 5 (expt x 3))))
(lambda (x) (> x 400)))

View file

@ -0,0 +1,21 @@
import std.stdio, std.math, std.conv, std.algorithm, std.array;
double f(in double x) pure nothrow {
return x.abs.sqrt + 5 * x ^^ 3;
}
void main() {
double[] data;
while (true) {
"Please enter eleven numbers on a line: ".write;
data = readln.split.map!(to!double).array;
if (data.length == 11)
break;
writeln("Those aren't eleven numbers.");
}
foreach_reverse (immutable x; data) {
immutable y = x.f;
writefln("f(%0.3f) = %s", x, y > 400 ? "Too large" : y.text);
}
}

View file

@ -0,0 +1,24 @@
procedure DoPardoKnuth(Memo: TMemo; A: array of double);
var Y: double;
var I: integer;
var S: string;
function Func(T: double): double;
begin
Result:=Sqrt(abs(T))+ 5*T*T*T;
end;
begin
for I:=0 to High(A) do
begin
Y:=Func(A[I]);
if y > 400 then S:='Too Large'
else S:=Format('%f %f',[A[I],Y]);
Memo.Lines.Add(S);
end;
end;
procedure ShowPardoKnuth(Memo: TMemo);
begin
DoPardoKnuth(Memo, [1,2,3,4,5,6,7,8,9,10,11]);
end;

View file

@ -0,0 +1,22 @@
!Trabb Pardo-Knuth algorithm
PROGRAM TPK
!VAR I%,Y
DIM A[10]
FUNCTION F(T)
F=SQR(ABS(T))+5*T^3
END FUNCTION
BEGIN
DATA(10,-1,1,2,3,4,4.3,4.305,4.303,4.302,4.301)
FOR I%=0 TO 10 DO
READ(A[I%])
END FOR
FOR I%=10 TO 0 STEP -1 DO
Y=F(A[I%])
PRINT("F(";A[I%];")=";)
IF Y>400 THEN PRINT("--->too large<---")
ELSE PRINT(Y)
END IF
END FOR
END PROGRAM

View file

@ -0,0 +1,18 @@
(define (trabb-fun n)
(+ (* 5 n n n) (sqrt(abs n))))
(define (check-trabb n)
(if (number? n)
(if (<= (trabb-fun n) 400)
(printf "🌱 f(%d) = %d" n (trabb-fun n))
(printf "❌ f(%d) = %d" n (trabb-fun n)))
(error "not a number" n)))
(define (trabb (numlist null))
(while (< (length numlist) 11)
(set! numlist (append numlist
(or
(read default: (shuffle (iota 11))
prompt: (format "Please enter %d more numbers" (- 11 (length numlist))))
(error 'incomplete-list numlist))))) ;; users cancel
(for-each check-trabb (reverse (take numlist 11))))

View file

@ -0,0 +1,20 @@
(trabb)
;; input : (0 4 1 8 5 9 10 3 6 7 2)
🌱 f(2) = 41.41421356237309
❌ f(7) = 1717.6457513110645
❌ f(6) = 1082.4494897427833
🌱 f(3) = 136.73205080756887
❌ f(10) = 5003.162277660168
❌ f(9) = 3648
❌ f(5) = 627.2360679774998
❌ f(8) = 2562.828427124746
🌱 f(1) = 6
🌱 f(4) = 322
🌱 f(0) = 0
;; extra credit : let's find the threshold
(lib 'math)
(define (g x) (- (trabb-fun x) 400))
(root g 0 10)
→ 4.301409367213084

View file

@ -0,0 +1,24 @@
open monad io number string
:::IO
take_numbers 0 xs = do
return $ iter xs
where f x = sqrt (toSingle x) + 5.0 * (x ** 3.0)
p x = x < 400.0
iter [] = return ()
iter (x::xs)
| p res = do
putStrLn (format "f({0}) = {1}" x res)
iter xs
| else = do
putStrLn (format "f({0}) :: Overflow" x)
iter xs
where res = f x
take_numbers n xs = do
x <- readAny
take_numbers (n - 1) (x::xs)
do
putStrLn "Please enter 11 numbers:"
take_numbers 11 []

View file

@ -0,0 +1,29 @@
import extensions;
import extensions'math;
public program()
{
real[] inputs := new real[](11);
console.printLine("Please enter 11 numbers :");
for(int i := 0, i < 11, i += 1)
{
inputs[i] := console.readLine().toReal()
};
console.printLine("Evaluating f(x) = |x|^0.5 + 5x^3 for the given inputs :");
for(int i := 10, i >= 0, i -= 1)
{
real result := sqrt(abs(inputs[i])) + 5 * power(inputs[i], 3);
console.print("f(", inputs[i], ")=");
if (result > 400)
{
console.printLine("Overflow!")
}
else
{
console.printLine(result)
}
}
}

View file

@ -0,0 +1,24 @@
defmodule Trabb_Pardo_Knuth do
def task do
Enum.reverse( get_11_numbers )
|> Enum.each( fn x -> perform_operation( &function(&1), 400, x ) end )
end
defp alert( n ), do: IO.puts "Operation on #{n} overflowed"
defp get_11_numbers do
ns = IO.gets( "Input 11 integers. Space delimited, please: " )
|> String.split
|> Enum.map( &String.to_integer &1 )
if 11 == length( ns ), do: ns, else: get_11_numbers
end
defp function( x ), do: :math.sqrt( abs(x) ) + 5 * :math.pow( x, 3 )
defp perform_operation( fun, overflow, n ), do: perform_operation_check_overflow( n, fun.(n), overflow )
defp perform_operation_check_overflow( n, result, overflow ) when result > overflow, do: alert( n )
defp perform_operation_check_overflow( n, result, _overflow ), do: IO.puts "f(#{n}) => #{result}"
end
Trabb_Pardo_Knuth.task

View file

@ -0,0 +1,23 @@
-module( trabb_pardo_knuth ).
-export( [task/0] ).
task() ->
Sequence = get_11_numbers(),
S = lists:reverse( Sequence ),
[perform_operation( fun function/1, 400, X) || X <- S].
alert( N ) -> io:fwrite( "Operation on ~p overflowed~n", [N] ).
get_11_numbers() ->
{ok, Ns} = io:fread( "Input 11 integers. Space delimited, please: ", "~d ~d ~d ~d ~d ~d ~d ~d ~d ~d ~d" ),
11 = erlang:length( Ns ),
Ns.
function( X ) -> math:sqrt( erlang:abs(X) ) + 5 * math:pow( X, 3 ).
perform_operation( Fun, Overflow, N ) -> perform_operation_check_overflow( N, Fun(N), Overflow ).
perform_operation_check_overflow( N, Result, Overflow ) when Result > Overflow -> alert( N );
perform_operation_check_overflow( N, Result, _Overflow ) -> io:fwrite( "f(~p) => ~p~n", [N, Result] ).

View file

@ -0,0 +1,9 @@
module ``Trabb Pardo - Knuth``
open System
let f (x: float) = sqrt(abs x) + (5.0 * (x ** 3.0))
Console.WriteLine "Enter 11 numbers:"
[for _ in 1..11 -> Convert.ToDouble(Console.ReadLine())]
|> List.rev |> List.map f |> List.iter (function
| n when n <= 400.0 -> Console.WriteLine(n)
| _ -> Console.WriteLine("Overflow"))

View file

@ -0,0 +1,24 @@
USING: formatting io kernel math math.functions math.parser
prettyprint sequences splitting ;
IN: rosetta-code.trabb-pardo-knuth
CONSTANT: threshold 400
CONSTANT: prompt "Please enter 11 numbers: "
: fn ( x -- y ) [ abs 0.5 ^ ] [ 3 ^ 5 * ] bi + ;
: overflow? ( x -- ? ) threshold > ;
: get-input ( -- seq )
prompt write flush readln " " split dup length 11 =
[ drop get-input ] unless ;
: ?result ( ..a quot: ( ..a -- ..b ) -- ..b )
[ "f(%u) = " sprintf ] swap bi dup overflow?
[ drop "overflow" ] [ "%.3f" sprintf ] if append ; inline
: main ( -- )
get-input reverse
[ string>number [ fn ] ?result print ] each ;
MAIN: main

View file

@ -0,0 +1,40 @@
: f(x) fdup fsqrt fswap 3e f** 5e f* f+ ;
4e2 fconstant f-too-big
11 Constant #Elements
: float-array ( compile: n -- / run: n -- addr )
create
floats allot
does>
swap floats + ;
#Elements float-array vec
: get-it ( -- )
." Enter " #Elements . ." numbers:" cr
#Elements 0 DO
." > " pad 25 accept cr
pad swap >float 0= abort" Invalid Number"
i vec F!
LOOP ;
: reverse-it ( -- )
#Elements 2/ 0 DO
i vec F@ #Elements i - 1- vec F@
i vec F! #Elements i - 1- vec F!
LOOP ;
: do-it ( -- )
#Elements 0 DO
i vec F@ fdup f. [char] : emit space
f(x) fdup f-too-big f> IF
fdrop ." too large"
ELSE
f.
THEN cr
LOOP ;
: tpk ( -- )
get-it reverse-it do-it ;

View file

@ -0,0 +1,30 @@
program tpk
implicit none
real, parameter :: overflow = 400.0
real :: a(11), res
integer :: i
write(*,*) "Input eleven numbers:"
read(*,*) a
a = a(11:1:-1)
do i = 1, 11
res = f(a(i))
write(*, "(a, f0.3, a)", advance = "no") "f(", a(i), ") = "
if(res > overflow) then
write(*, "(a)") "overflow!"
else
write(*, "(f0.3)") res
end if
end do
contains
real function f(x)
real, intent(in) :: x
f = sqrt(abs(x)) + 5.0*x**3
end function
end program

View file

@ -0,0 +1,16 @@
C THE TPK ALGORITH - FORTRAN I - 1957 TPK00010
FTPKF(X)=SQRTF(ABSF(X))+5.0*X**3 TPK00020
DIMENSION A(11) TPK00030
READ 100,A TPK00040
100 FORMAT(6F12.4/) TPK00050
DO 3 I=1,11 TPK00060
J=12-I TPK00070
Y=FTPKF(A(J)) TPK00080
IF (Y-400.0)2,2,1 TPK00090
1 PRINT 301,I,A(J) TPK00100
301 FORMAT(I10,F12.7,18H *** TOO LARGE ***) TPK00110
GO TO 10 TPK00120
2 PRINT 302,I,A(J),Y TPK00130
302 FORMAT(I10,2F12.7) TPK00140
3 CONTINUE TPK00150
STOP 0 TPK00160

View file

@ -0,0 +1,37 @@
' version 22-07-2017
' compile with: fbc -s console
Function f(n As Double) As Double
return Sqr(Abs(n)) + 5 * n ^ 3
End Function
' ------=< MAIN >=------
Dim As Double x, s(1 To 11)
Dim As Long i
For i = 1 To 11
Print Str(i);
Input " => ", s(i)
Next
Print
Print String(20,"-")
i -= 1
Do
Print "f(" + Str(s(i)) + ") = ";
x = f(s(i))
If x > 400 Then
Print "-=< overflow >=-"
Else
Print x
End If
i -= 1
Loop Until i < 1
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End

View file

@ -0,0 +1,29 @@
// Trabb Pardo-Knuth algorithm
include "NSLog.incl"
local fn f( x as double ) as double
end fn = fn pow( abs(x), 0.5) + 5 * ( fn pow(x, 3) )
void local fn PardoKnuth( userInput as double )
double x = userInput
double y = fn f(x)
NSLog( @"f(%.4f)\t= \b", x )
if( y < 400.0 )
NSLog( @"%.4f", y )
else
NSLog( @"[Overflow]" )
end if
end fn
NSUInteger i
CFArrayRef numbers
numbers = @[@10, @-1, @1, @2, @3 ,@4, @4.3, @4.305, @4.303, @4.302, @4.301]
NSLog( @"Please enter 11 numbers:" )
for i = len(numbers) to 1 step -1
fn PardoKnuth( fn NumberDoubleValue( numbers[i-1] ) )
next
HandleEvents

View file

@ -0,0 +1,21 @@
10 REM Trabb Pardo-Knuth algorithm
20 REM Used "magic numbers" because of strict specification of the algorithm.
30 DEF FNF(N) = SQR(ABS(N)) + 5 * N * N * N
40 DIM S(10)
50 PRINT "Enter 11 numbers."
60 FOR I% = 0 TO 10
70 PRINT STR$(I%+1);
80 INPUT S(I%)
90 NEXT I%
100 PRINT
110 REM Reverse
120 FOR I% = 0 TO 10 \ 2
130 TMP = S(I%): S(I%) = S(10 - I%): S(10 - I%) = TMP
160 NEXT I%
170 REM Results
180 FOR I% = 0 TO 10
190 PRINT "f(";STR$(S(I%));") =";
220 R = FNF(S(I%))
230 IF R > 400 THEN PRINT " overflow" ELSE PRINT R
240 NEXT I%
250 END

View file

@ -0,0 +1,38 @@
package main
import (
"fmt"
"log"
"math"
)
func main() {
// prompt
fmt.Print("Enter 11 numbers: ")
// accept sequence
var s [11]float64
for i := 0; i < 11; {
if n, _ := fmt.Scan(&s[i]); n > 0 {
i++
}
}
// reverse sequence
for i, item := range s[:5] {
s[i], s[10-i] = s[10-i], item
}
// iterate
for _, item := range s {
if result, overflow := f(item); overflow {
// send alerts to stderr
log.Printf("f(%g) overflow", item)
} else {
// send normal results to stdout
fmt.Printf("f(%g) = %g\n", item, result)
}
}
}
func f(x float64) (float64, bool) {
result := math.Sqrt(math.Abs(x)) + 5*x*x*x
return result, result > 400
}

View file

@ -0,0 +1,24 @@
package main
import (
"fmt"
"math"
)
func f(t float64) float64 {
return math.Sqrt(math.Abs(t)) + 5*math.Pow(t, 3)
}
func main() {
var a [11]float64
for i := range a {
fmt.Scan(&a[i])
}
for i := len(a) - 1; i >= 0; i-- {
if y := f(a[i]); y > 400 {
fmt.Println(i, "TOO LARGE")
} else {
fmt.Println(i, y)
}
}
}

View file

@ -0,0 +1,16 @@
import Control.Monad (replicateM, mapM_)
f :: Floating a => a -> a
f x = sqrt (abs x) + 5 * x ** 3
main :: IO ()
main = do
putStrLn "Enter 11 numbers for evaluation"
x <- replicateM 11 readLn
mapM_
((\x ->
if x > 400
then putStrLn "OVERFLOW"
else print x) .
f) $
reverse x

View file

@ -0,0 +1,11 @@
procedure main()
S := []
writes("Enter 11 numbers: ")
read() ? every !11 do (tab(many(' \t'))|0,put(S, tab(upto(' \t')|0)))
every item := !reverse(S) do
write(item, " -> ", (400 >= f(item)) | "overflows")
end
procedure f(x)
return abs(x)^0.5 + 5*x^3
end

View file

@ -0,0 +1,23 @@
// Initialize objects to be used
in_num := File standardInput()
nums := List clone
result := Number
// Prompt the user and get numbers from standard input
"Please enter 11 numbers:" println
11 repeat(nums append(in_num readLine() asNumber()))
// Reverse the numbers received
nums reverseInPlace
// Apply the function and tell the user if the result is above
// our limit. Otherwise, tell them the result.
nums foreach(v,
// v needs parentheses around it for abs to properly convert v to its absolute value
result = (v) abs ** 0.5 + 5 * v ** 3
if (result > 400,
"Overflow!" println
,
result println
)
)

View file

@ -0,0 +1,6 @@
tpk=: 3 :0
smoutput 'Enter 11 numbers: '
t1=: ((5 * ^&3) + (^&0.5@* *))"0 |. _999&".;._1 ' ' , 1!:1 [ 1
smoutput 'Values of functions of reversed input: ' , ": t1
; <@(,&' ')@": ` ((<'user alert ')&[) @. (>&400)"0 t1
)

View file

@ -0,0 +1,5 @@
tpk ''
Enter 11 numbers:
1 2 3 4 5 6 7 8.8 _9 10.123 0
Values of functions of reversed input: 0 5189.96 _3642 3410.33 1717.65 1082.45 627.236 322 136.732 41.4142 6
0 user alert _3642 user alert user alert user alert user alert 322 136.732 41.4142 6

View file

@ -0,0 +1,10 @@
get11numbers=: 3 :0
smoutput 'Enter 11 numbers: '
_&". 1!:1]1
)
f_x=: %:@| + 5 * ^&3
overflow400=: 'user alert'"_`":@.(<:&400)"0
tpk=: overflow400@f_x@|.@get11numbers

View file

@ -0,0 +1,14 @@
tpk''
Enter 11 numbers:
1 2 3 4 5 6 7 8.8 _9 10.123 0
0
user alert
_3642
user alert
user alert
user alert
user alert
322
136.732
41.4142
6

View file

@ -0,0 +1,36 @@
/**
* Alexander Alvonellos
*/
import java.util.*;
import java.io.*;
public class TPKA {
public static void main(String... args) {
double[] input = new double[11];
double userInput = 0.0;
Scanner in = new Scanner(System.in);
for(int i = 0; i < 11; i++) {
System.out.print("Please enter a number: ");
String s = in.nextLine();
try {
userInput = Double.parseDouble(s);
} catch (NumberFormatException e) {
System.out.println("You entered invalid input, exiting");
System.exit(1);
}
input[i] = userInput;
}
for(int j = 10; j >= 0; j--) {
double x = input[j]; double y = f(x);
if( y < 400.0) {
System.out.printf("f( %.2f ) = %.2f\n", x, y);
} else {
System.out.printf("f( %.2f ) = %s\n", x, "TOO LARGE");
}
}
}
private static double f(double x) {
return Math.pow(Math.abs(x), 0.5) + (5*(Math.pow(x, 3)));
}
}

View file

@ -0,0 +1,36 @@
#!/usr/bin/env js
function main() {
var nums = getNumbers(11);
nums.reverse();
for (var i in nums) {
pardoKnuth(nums[i], fn, 400);
}
}
function pardoKnuth(n, f, max) {
var res = f(n);
putstr('f(' + String(n) + ')');
if (res > max) {
print(' is too large');
} else {
print(' = ' + String(res));
}
}
function fn(x) {
return Math.pow(Math.abs(x), 0.5) + 5 * Math.pow(x, 3);
}
function getNumbers(n) {
var nums = [];
print('Enter', n, 'numbers.');
for (var i = 1; i <= n; i++) {
putstr(' ' + i + ': ');
var num = readline();
nums.push(Number(num));
}
return nums;
}
main();

View file

@ -0,0 +1,11 @@
def f:
def abs: if . < 0 then -. else . end;
def power(x): (x * log) | exp;
. as $x | abs | power(0.5) + (5 * (.*.*. ));
. as $in | split(" ") | map(tonumber)
| if length == 11 then
reverse | map(f | if . > 400 then "TOO LARGE" else . end)
else error("The number of numbers was not 11.")
end
| .[] # print one result per line

View file

@ -0,0 +1,15 @@
$ echo "Enter 11 numbers on one line; when done, enter the end-of-file character:" ;\
jq -M -s -R -f Trabb_Pardo-Knuth_algorithm.jq
> Enter 11 numbers on one line; when done, enter the end-of-file character:
1 2 3 4 5 6 7 8 9 10 11
"TOO LARGE"
"TOO LARGE"
"TOO LARGE"
"TOO LARGE"
"TOO LARGE"
"TOO LARGE"
"TOO LARGE"
322
136.73205080756887
41.41421356237309
6

View file

@ -0,0 +1,5 @@
f(x) = √abs(x) + 5x^3
for i in reverse(split(readline()))
v = f(parse(Int, i))
println("$(i): ", v > 400 ? "TOO LARGE" : v)
end

View file

@ -0,0 +1,29 @@
// version 1.1.2
fun f(x: Double) = Math.sqrt(Math.abs(x)) + 5.0 * x * x * x
fun main(args: Array<String>) {
val da = DoubleArray(11)
println("Please enter 11 numbers:")
var i = 0
while (i < 11) {
print(" ${"%2d".format(i + 1)}: ")
val d = readLine()!!.toDoubleOrNull()
if (d == null)
println("Not a valid number, try again")
else
da[i++] = d
}
println("\nThe sequence you just entered in reverse is:")
da.reverse()
println(da.contentToString())
println("\nProcessing this sequence...")
for (j in 0..10) {
val v = f(da[j])
print(" ${"%2d".format(j + 1)}: ")
if (v > 400.0)
println("Overflow!")
else
println(v)
}
}

View file

@ -0,0 +1,52 @@
#!/bin/ksh
# Trabb PardoKnuth algorithm
# # Variables:
#
integer NUM_ELE=11
typeset -F FUNC_LIMIT=400
# # Functions:
#
# # Function _input(_arr) - Ask for user input, build array
#
function _input {
typeset _arr ; nameref _arr="$1"
typeset _i ; integer _i
clear ; print "Please input 11 numbers..."
for ((_i=1 ; _i<=NUM_ELE ; _i++)); do
read REPLY?"${_i}: "
[[ $REPLY != {,1}(-)+(\d){,1}(.)*(\d) ]] && ((_i--)) && continue
_arr+=( $REPLY )
done
}
# # Function _function() - Apply |x|^0.5 + 5x^3
# # note: >400 creates an overflow situation
#
function _function {
typeset _x ; _x=$1
(( _result = sqrt(abs(${_x})) + 5 * _x * _x * _x ))
(( _result <= $FUNC_LIMIT )) && echo ${_result} && return 0
return 1
}
######
# main #
######
typeset -a inputarr
_input inputarr
integer i
printf "%s\n\n" "Evaluating f(x) = |x|^0.5 + 5x^3 for the given inputs :"
for (( i=NUM_ELE-1; i>=0; i-- )); do
result=$(_function ${inputarr[i]})
if (( $? )); then
printf "%s\n" "Overflow"
else
printf "%s\n" "${result}"
fi
done

View file

@ -0,0 +1,30 @@
' Trabb Pardo-Knuth algorithm
' Used "magic numbers" because of strict specification of the algorithm.
dim s(10)
print "Enter 11 numbers."
for i = 0 to 10
print i + 1;
input " => "; s(i)
next i
print
' Reverse
for i = 0 to 10 / 2
tmp = s(i)
s(i) = s(10 - i)
s(10 - i) = tmp
next i
'Results
for i = 0 to 10
print "f("; s(i); ") = ";
r = f(s(i))
if r > 400 then
print "overflow"
else
print r
end if
next i
end
function f(n)
f = sqr(abs(n)) + 5 * n * n * n
end function

View file

@ -0,0 +1,18 @@
function f (x) return math.abs(x)^0.5 + 5*x^3 end
function reverse (t)
local rev = {}
for i, v in ipairs(t) do rev[#t - (i-1)] = v end
return rev
end
local sequence, result = {}
print("Enter 11 numbers...")
for n = 1, 11 do
io.write(n .. ": ")
sequence[n] = io.read()
end
for _, x in ipairs(reverse(sequence)) do
result = f(x)
if result > 400 then print("Overflow!") else print(result) end
end

View file

@ -0,0 +1,10 @@
local a, y = {}
function f (t)
return math.sqrt(math.abs(t)) + 5*t^3
end
for i = 0, 10 do a[i] = io.read() end
for i = 10, 0, -1 do
y = f(a[i])
if y > 400 then print(i, "TOO LARGE")
else print(i, y) end
end

View file

@ -0,0 +1,27 @@
Module Input11 {
Flush ' empty stack
For I=1 to 11 {
Input "Give me a number ", a
Data a ' add to bottom of stack, use: Push a to add to top, to get reverse order here
}
}
Module Run {
Print "Trabb PardoKnuth algorithm"
Print "f(x)=Sqrt(Abs(x))+5*x^3"
if not match("NNNNNNNNN") then Error "Need 11 numbers"
Shiftback 1, -11 ' reverse order 11 elements of stack of values
Def f(x)=Sqrt(Abs(x))+5*x^3
For i=1 to 11 {
Read pop
y=f(pop)
if y>400 Then {
Print format$("f({0}) = Overflow!", pop)
} Else {
Print format$("f({0}) = {1}", pop, y)
}
}
}
Run 10, -1, 1, 2, 3, 4, 4.3, 4.305, 4.303, 4.302, 4.301
Run 1, 2, 3, -4.55,5.1111, 6, -7, 8, 9, 10, 11
Input11
Run

View file

@ -0,0 +1,24 @@
Global a$
Document a$ ' make a$ as a document - string with paragraphs
Module Run {
a$<={Trabb PardoKnuth algorithm
f(x)=Sqrt(Abs(x))+5*x^3
}
if not match("NNNNNNNNN") then Error "Need 11 numbers"
Shiftback 1, -11 ' reverse order 11 elements of stack of values
Def f(x)=Sqrt(Abs(x))+5*x^3
For i=1 to 11 {
Read pop
y=f(pop)
if y>400 Then {
a$<=format$("f({0}) = Overflow!", pop)+{
}
} Else {
a$<=format$("f({0}) = {1}", pop, y)+{
}
}
}
}
Run 10, -1, 1, 2, 3, 4, 4.3, 4.305, 4.303, 4.302, 4.301
Run 1, 2, 3, -4.55,5.1111, 6, -7, 8, 9, 10, 11
Clipboard a$

View file

@ -0,0 +1,10 @@
seqn := ListTools:-Reverse([parse(Maplets[Display](Maplets:-Elements:-Maplet(Maplets:-Elements:-InputDialog['ID1']("Enter a sequence of numbers separated by comma", 'onapprove' = Maplets:-Elements:-Shutdown(['ID1']), 'oncancel' = Maplets:-Elements:-Shutdown())))[1])]):
f:= x -> abs(x)^0.5 + 5*x^3:
for item in seqn do
result := f(item):
if (result > 400) then
print("Alert: Overflow."):
else
print(result):
end if:
end do:

View file

@ -0,0 +1,15 @@
numbers=RandomReal[{-2,6},11]
tpk[numbers_,overflowVal_]:=Module[{revNumbers},
revNumbers=Reverse[numbers];
f[x_]:=Abs[x]^0.5+5 x^3;
Do[
If[f[i]>overflowVal,
Print["f[",i,"]= Overflow"]
,
Print["f[",i,"]= ",f[i]]
]
,
{i,revNumbers}
]
]
tpk[numbers,400]

View file

@ -0,0 +1,5 @@
((0 <) (-1 *) when) :abs
(((abs 0.5 pow) (3 pow 5 * +)) cleave) :fn
"Enter 11 numbers:" puts!
(gets float) 11 times
(fn (400 <=) (pop "Overflow") unless puts!) 11 times

View file

@ -0,0 +1,27 @@
10 REM Trabb Pardo-Knuth algorithm
20 REM Used "magic numbers" because of strict specification
30 REM of the algorithm.
40 DEF FNF(N) = SQR(ABS(N))+5*N*N*N
50 DIM S(10)
60 PRINT "Enter 11 numbers."
70 FOR I = 0 TO 10
80 PRINT I+1; "- Enter number";
90 INPUT S(I)
100 NEXT I
110 PRINT
120 REM Reverse
130 FOR I = 0 TO 10/2
140 LET T = S(I)
150 LET S(I) = S(10-I)
160 LET S(10-I) = T
170 NEXT I
180 REM Results
190 PRINT "num", "f(num)"
200 FOR I = 0 TO 10
210 LET R = FNF(S(I))
220 IF R>400 THEN 250
230 PRINT S(I), R
240 GOTO 260
250 PRINT S(I), " overflow"
260 NEXT I
270 END

View file

@ -0,0 +1,25 @@
10 REM Trabb Pardo-Knuth algorithm
20 REM Used "magic numbers" because of strict
30 REM specification of the algorithm.
40 DEF FNF(N)=SQR(ABS(N))+5*N*N*N
50 DIM S(10)
60 PRINT "Enter 11 numbers."
70 FOR I=0 TO 10
80 PRINT STR$(I+1);
90 INPUT S(I)
100 NEXT I
110 PRINT
120 REM ** Reverse
130 FOR I=0 TO 10/2
140 TMP=S(I)
150 S(I)=S(10-I)
160 S(10-I)=TMP
170 NEXT I
180 REM ** Results
190 FOR I=0 TO 10
200 PRINT "f(";STR$(S(I));") =";
210 R=FNF(S(I))
220 IF R>400 THEN PRINT " overflow":GOTO 240
230 PRINT R
240 NEXT I
250 END

View file

@ -0,0 +1,12 @@
import math, rdstdin, strutils, algorithm, sequtils
proc f(x: float): float = x.abs.pow(0.5) + 5 * x.pow(3)
proc ask: seq[float] =
readLineFromStdin("11 numbers: ").strip.split[0..10].map(parseFloat)
var s = ask()
reverse s
for x in s:
let result = f(x)
echo x, ": ", if result > 400: "TOO LARGE!" else: $result

View file

@ -0,0 +1,12 @@
let f x = sqrt x +. 5.0 *. (x ** 3.0)
let p x = x < 400.0
let () =
print_endline "Please enter 11 Numbers:";
let lst = Array.to_list (Array.init 11 (fun _ -> read_float ())) in
List.iter (fun x ->
let res = f x in
if p res
then Printf.printf "f(%g) = %g\n%!" x res
else Printf.eprintf "f(%g) :: Overflow\n%!" x
) (List.rev lst)

View file

@ -0,0 +1,41 @@
//
// TPKA.m
// RosettaCode
//
// Created by Alexander Alvonellos on 5/26/12.
// Trabb Pardo-Knuth algorithm
//
#import <Foundation/Foundation.h>
double f(double x);
double f(double x) {
return pow(abs(x), 0.5) + 5*(pow(x, 3));
}
int main (int argc, const char * argv[])
{
@autoreleasepool {
NSMutableArray *input = [[NSMutableArray alloc] initWithCapacity:0];
printf("%s", "Instructions: please enter 11 numbers.\n");
for(int i = 0; i < 11; i++) {
double userInput = 0.0;
printf("%s", "Please enter a number: ");
scanf("%lf", &userInput);
[input addObject: @(userInput)];
}
for(int i = 10; i >= 0; i--) {
double x = [input[i] doubleValue];
double y = f(x);
printf("f(%.2f) \t=\t", x);
if(y < 400.0) {
printf("%.2f\n", y);
} else {
printf("%s\n", "TOO LARGE");
}
}
}
return 0;
}

View file

@ -0,0 +1,6 @@
{
print("11 numbers: ");
v=vector(11, n, eval(input()));
v=apply(x->x=sqrt(abs(x))+5*x^3;if(x>400,"overflow",x), v);
vector(11, i, v[12-i])
}

View file

@ -0,0 +1,28 @@
<?php
// Trabb Pardo-Knuth algorithm
// Used "magic numbers" because of strict specification of the algorithm.
function f($n)
{
return sqrt(abs($n)) + 5 * $n * $n * $n;
}
$sArray = [];
echo "Enter 11 numbers.\n";
for ($i = 0; $i <= 10; $i++) {
echo $i + 1, " - Enter number: ";
array_push($sArray, (float)fgets(STDIN));
}
echo PHP_EOL;
// Reverse
$sArray = array_reverse($sArray);
// Results
foreach ($sArray as $s) {
$r = f($s);
echo "f(", $s, ") = ";
if ($r > 400)
echo "overflow\n";
else
echo $r, PHP_EOL;
}
?>

View file

@ -0,0 +1,25 @@
Trabb: Procedure options (main); /* 11 November 2013 */
declare (i, n) fixed binary;
declare s fixed (5,1) controlled;
declare g fixed (15,5);
put ('Please type 11 values:');
do i = 1 to 11;
allocate s;
get (s);
put (s);
end;
put skip(2) ('Results:');
do i = 1 to 11;
g = f(s); put skip list (s);
if g > 400 then put ('Too large'); else put (g);
free s;
end;
f: procedure (x) returns (fixed(15,5));
declare x fixed (5,1);
return (sqrt(abs(x)) + 5*x**3);
end f;
end Trabb;

View file

@ -0,0 +1,28 @@
TPK: DO;
/* external I/O and real mathematical routines */
WRITE$STRING: PROCEDURE( S ) EXTERNAL; DECLARE S POINTER; END;
WRITE$REAL: PROCEDURE( R ) EXTERNAL; DECLARE R REAL; END;
WRITE$NL: PROCEDURE EXTERNAL; END;
READ$REAL: PROCEDURE( R ) REAL EXTERNAL; DECLARE R POINTER; END;
REAL$ABS: PROCEDURE( R ) REAL EXTERNAL; DECLARE R REAL; END;
REAL$SQRT: PROCEDURE( R ) REAL EXTERNAL; DECLARE R REAL; END;
/* end external routines */
F: PROCEDURE( T ) REAL;
DECLARE T REAL;
RETURN REAL$SQRT(REAL$ABS(T))+5*T*T*T;
END F;
MAIN: PROCEDURE;
DECLARE Y REAL, A( 11 ) REAL, I INTEGER;
DO I = 0 TO 10;
CALL READ$REAL( @A( I ) );
END;
DO I = 10 TO 0 BY -1;
Y = F( A( I ) );
IF Y > 400.0 THEN CALL WRITE$STRING( @( 'TOO LARGE', 0 ) );
ELSE CALL WRITE$REAL( Y );
CALL WRITE$NL();
END;
END MAIN;
END TPK;

View file

@ -0,0 +1,11 @@
print "Enter 11 numbers:\n";
for ( 1..11 ) {
$number = <STDIN>;
chomp $number;
push @sequence, $number;
}
for $n (reverse @sequence) {
my $result = sqrt( abs($n) ) + 5 * $n**3;
printf "f( %6.2f ) %s\n", $n, $result > 400 ? " too large!" : sprintf "= %6.2f", $result
}

View file

@ -0,0 +1,27 @@
(phixonline)-->
<span style="color: #008080;">function</span> <span style="color: #000000;">f</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">x</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #7060A8;">sqrt</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">abs</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">))+</span><span style="color: #000000;">5</span><span style="color: #0000FF;">*</span><span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</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;">test</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">bool</span> <span style="color: #000000;">fake_prompt</span><span style="color: #0000FF;">=</span><span style="color: #004600;">true</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">fake_prompt</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;">"Enter 11 numbers:%s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">s</span><span style="color: #0000FF;">})</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">substitute</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #008000;">","</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" "</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">S</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">scanf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%f %f %f %f %f %f %f %f %f %f %f"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">S</span><span style="color: #0000FF;">)!=</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</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;">"not 11 numbers"</span><span style="color: #0000FF;">)</span> <span style="color: #7060A8;">abort</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">S</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">reverse</span><span style="color: #0000FF;">(</span><span style="color: #000000;">S</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">])</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">S</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">result</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">f</span><span style="color: #0000FF;">(</span><span style="color: #000000;">S</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">result</span><span style="color: #0000FF;">></span><span style="color: #000000;">400</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;">"f(%g):overflow\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">S</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</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: #008000;">"f(%g):%g\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">S</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #000000;">result</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;">procedure</span>
<span style="color: #000080;font-style:italic;">--test(prompt_string("Enter 11 numbers:"),false)</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">tests</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #008000;">"10 -1 1 2 3 4 4.3 4.305 4.303 4.302 4.301"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"1,2,3,4,5,6,7,8,9,10,11"</span><span style="color: #0000FF;">,</span>
<span style="color: #008000;">"0.470145,1.18367,2.36984,4.86759,2.40274,5.48793,3.30256,5.34393,4.21944,2.23501,-0.0200707"</span><span style="color: #0000FF;">}</span>
<span style="color: #7060A8;">papply</span><span style="color: #0000FF;">(</span><span style="color: #000000;">tests</span><span style="color: #0000FF;">,</span><span style="color: #000000;">test</span><span style="color: #0000FF;">)</span>
<!--

View file

@ -0,0 +1,9 @@
import util.
go =>
L = [I.parse_term() : I in split(read_line())],
S = [[I,cond(F<=400,F,'TOO LARGE')] : I in L.len..-1..1, F=f(L[I])],
println(S),
nl.
f(T) = sqrt(abs(T)) + 5*T**3.

View file

@ -0,0 +1,10 @@
(de f (X)
(+ (sqrt (abs X)) (* 5 X X X)) )
(trace 'f)
(in NIL
(prin "Input 11 numbers: ")
(for X (reverse (make (do 11 (link (read)))))
(when (> (f X) 400)
(prinl "TOO LARGE") ) ) )

View file

@ -0,0 +1,30 @@
Input 11 numbers: 1 2 3 4 5 6 7 8 9 10 11
f : 11
f = 6658
TOO LARGE
f : 10
f = 5003
TOO LARGE
f : 9
f = 3648
TOO LARGE
f : 8
f = 2562
TOO LARGE
f : 7
f = 1717
TOO LARGE
f : 6
f = 1082
TOO LARGE
f : 5
f = 627
TOO LARGE
f : 4
f = 322
f : 3
f = 136
f : 2
f = 41
f : 1
f = 6

View file

@ -0,0 +1,49 @@
function Get-Tpk
{
[CmdletBinding()]
[OutputType([PSCustomObject])]
Param
(
[Parameter(Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]
[double]
$Number
)
Begin
{
function Get-TpkFunction ([double]$Number)
{
[Math]::Pow([Math]::Abs($Number),(0.5)) + 5 * [Math]::Pow($Number,3)
}
[object[]]$output = @()
}
Process
{
$Number | ForEach-Object {
$n = Get-TpkFunction $_
if ($n -le 400)
{
$result = $n
}
else
{
$result = "Overflow"
}
}
$output += [PSCustomObject]@{
Number = $Number
Result = $result
}
}
End
{
[Array]::Reverse($output)
$output
}
}

View file

@ -0,0 +1,2 @@
$tpk = 1..11 | Get-Tpk
$tpk

View file

@ -0,0 +1 @@
$tpk | where result -ne overflow | sort number

View file

@ -0,0 +1,52 @@
Procedure.d f(x.d)
ProcedureReturn Pow(Abs(x), 0.5) + 5 * x * x * x
EndProcedure
Procedure split(i.s, delimeter.s, List o.d())
Protected index = CountString(i, delimeter) + 1 ;add 1 because last entry will not have a delimeter
While index > 0
AddElement(o())
o() = ValD(Trim(StringField(i, index, delimeter)))
index - 1
Wend
ProcedureReturn ListSize(o())
EndProcedure
Define i$, entriesAreValid = 0, result.d, output$
NewList numbers.d()
If OpenConsole()
Repeat
PrintN(#crlf$ + "Enter eleven numbers that are each separated by spaces or commas:")
i$ = Input(
i$ = Trim(i$)
If split(i$, ",", numbers.d()) < 11
ClearList(numbers())
If split(i$, " ", numbers.d()) < 11
PrintN("Not enough numbers were supplied.")
ClearList(numbers())
Else
entriesAreValid = 1
EndIf
Else
entriesAreValid = 1
EndIf
Until entriesAreValid = 1
ForEach numbers()
output$ = "f(" + RTrim(RTrim(StrD(numbers(), 3), "0"), ".") + ") = "
result.d = f(numbers())
If result > 400
output$ + "Too Large"
Else
output$ + RTrim(RTrim(StrD(result, 3), "0"), ".")
EndIf
PrintN(output$)
Next
Print(#crlf$ + #crlf$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf

View file

@ -0,0 +1,10 @@
Python 3.2.2 (default, Sep 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> def f(x): return abs(x) ** 0.5 + 5 * x**3
>>> print(', '.join('%s:%s' % (x, v if v<=400 else "TOO LARGE!")
for x,v in ((y, f(float(y))) for y in input('\nnumbers: ').strip().split()[:11][::-1])))
11 numbers: 1 2 3 4 5 6 7 8 9 10 11
11:TOO LARGE!, 10:TOO LARGE!, 9:TOO LARGE!, 8:TOO LARGE!, 7:TOO LARGE!, 6:TOO LARGE!, 5:TOO LARGE!, 4:322.0, 3:136.73205080756887, 2:41.41421356237309, 1:6.0
>>>

View file

@ -0,0 +1,15 @@
import math
def f(x):
return math.sqrt(abs(x)) + 5 * x**3
def ask_numbers(n=11):
print(f'Enter {n} numbers:')
return (float(input('>')) for _ in range(n))
if __name__ == '__main__':
for x in ask_numbers().reverse():
if (result := f(x)) > 400:
print(f'f({x}): overflow')
else:
print(f'f({x}) = {result}')

View file

@ -0,0 +1,25 @@
FUNCTION f (n!)
f = SQR(ABS(n)) + 5 * n ^ 3
END FUNCTION
DIM s(1 TO 11)
PRINT "enter 11 numbers"
FOR i = 1 TO 11
PRINT STR$(i);
INPUT " => ", s(i)
NEXT i
PRINT : PRINT STRING$(20, "-")
i = i - 1
DO
PRINT "f("; STR$(s(i)); ") = ";
x = f(s(i))
IF x > 400 THEN
PRINT "-=< overflow >=-"
ELSE
PRINT x
END IF
i = i - 1
LOOP UNTIL i < 1
END

View file

@ -0,0 +1,18 @@
[ $ "bigrat.qky" loadfile ] now!
[ $->v drop
2dup vabs 10 vsqrt drop
2swap 2dup 2dup
v* v* 5 n->v v* v+ ] is function ( $ --> n/d )
[ $ "Please enter 11 numbers: "
input nest$
reverse
witheach
[ function
400 n->v 2over v< iff
[ 2drop say "overflow" ]
else
[ 7 point$ echo$ ]
sp ]
cr ] is task ( --> )

View file

@ -0,0 +1,11 @@
S <- scan(n=11)
f <- function(x) sqrt(abs(x)) + 5*x^3
for (i in rev(S)) {
res <- f(i)
if (res > 400)
print("Too large!")
else
print(res)
}

View file

@ -0,0 +1,48 @@
/*REXX program implements the Trabb─Pardo-Knuth algorithm for N numbers (default is 11).*/
numeric digits 200 /*the number of digits precision to use*/
parse arg N .; if N=='' | N=="," then N=11 /*Not specified? Then use the default.*/
maxValue= 400 /*the maximum value f(x) can have. */
wid= 20 /* ··· but only show this many digits.*/
frac= 5 /* ··· show this # of fractional digs.*/
say ' _____' /* ◄─── this SAY displays a vinculum.*/
say 'function: ƒ(x) x + (5 * x^3)'
prompt= 'enter ' N " numbers for the Trabb─Pardo─Knuth algorithm: (or Quit)"
do ask=0; say; /*░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░*/
say prompt; say; pull $; say /**/
if abbrev('QUIT',$,1) then do; say 'quitting.'; exit 1; end /**/
ok=0 /**/
select /*validate there're N numbers.*/ /**/
when $='' then say "no numbers entered" /**/
when words($)<N then say "not enough numbers entered" /**/
when words($)>N then say "too many numbers entered" /**/
otherwise ok=1 /**/
end /*select*/ /**/
if \ok then iterate /* [↓] W=max width. */ /**/
w=0; do v=1 for N; _=word($, v); w=max(w, length(_) ) /**/
if datatype(_, 'N') then iterate /*numeric ?*/ /**/
say _ "isn't numeric"; iterate ask /**/
end /*v*/ /**/
leave /**/
end /*ask*/ /*░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░*/
say 'numbers entered: ' $
say
do i=N by -1 for N; #=word($, i) / 1 /*process the numbers in reverse. */
g = fmt( f( # ) ) /*invoke function ƒ with arg number.*/
gw=right( 'ƒ('#") ", w+7) /*nicely formatted ƒ(number). */
if g>maxValue then say gw "is > " maxValue ' ['space(g)"]"
else say gw " = " g
end /*i*/ /* [↑] display the result to terminal.*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
f: procedure; parse arg x; return sqrt( abs(x) ) + 5 * x**3
/*──────────────────────────────────────────────────────────────────────────────────────*/
fmt: z=right(translate(format(arg(1), wid, frac), 'e', "E"), wid) /*right adjust; use e*/
if pos(.,z)\==0 then z=left(strip(strip(z,'T',0),"T",.),wid) /*strip trailing 0 &.*/
return right(z, wid - 4*(pos('e', z)==0) ) /*adjust: no exponent*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); m.=9; numeric form; h=d+6
numeric digits; parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g *.5'e'_ % 2
do j=0 while h>9; m.j=h; h=h % 2 + 1; end /*j*/
do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/; return g

View file

@ -0,0 +1,12 @@
#lang racket
(define input
(for/list ([i 11])
(printf "Enter a number (~a of 11): " (+ 1 i))
(read)))
(for ([x (reverse input)])
(define res (+ (sqrt (abs x)) (* 5 (expt x 3))))
(if (> res 400)
(displayln "Overflow!")
(printf "f(~a) = ~a\n" x res)))

View file

@ -0,0 +1,6 @@
my @nums = prompt("Please type 11 space-separated numbers: ").words
until @nums == 11;
for @nums.reverse -> $n {
my $r = $n.abs.sqrt + 5 * $n ** 3;
say "$n\t{ $r > 400 ?? 'Urk!' !! $r }";
}

View file

@ -0,0 +1,28 @@
# Project : Trabb PardoKnuth algorithm
decimals(3)
x = list(11)
for n=1 to 11
x[n] = n
next
s = [-5, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6]
for i = 1 to 11
see string(i) + " => " + s[i] + nl
next
see copy("-", 20) + nl
i = i - 1
while i > 0
see "f(" + string(s[i]) + ") = "
x = f(s[i])
if x > 400
see "-=< overflow >=-" + nl
else
see x + nl
ok
i = i - 1
end
func f(n)
return sqrt(fabs(n)) + 5 * pow(n, 3)

View file

@ -0,0 +1,10 @@
def f(x) x.abs ** 0.5 + 5 * x ** 3 end
puts "Please enter 11 numbers:"
nums = 11.times.map{ gets.to_f }
nums.reverse_each do |n|
print "f(#{n}) = "
res = f(n)
puts res > 400 ? "Overflow!" : res
end

View file

@ -0,0 +1,22 @@
dim s(10)
print "Enter 11 numbers."
for i = 0 to 10
print i +1;
input " => "; s(i)
next i
print
'Results
for i = 10 to 0 step -1
print "f("; s(i); ") = ";
r = f(s(i))
if r > 400 then
print "-=< overflow >=-"
else
print r
end if
next i
end
function f(n)
f = sqr(abs(n)) + 5 * n * n * n
end function

View file

@ -0,0 +1,30 @@
use std::io::{self, BufRead};
fn op(x: f32) -> Option<f32> {
let y = x.abs().sqrt() + 5.0 * x * x * x;
if y < 400.0 {
Some(y)
} else {
None
}
}
fn main() {
println!("Please enter 11 numbers (one number per line)");
let stdin = io::stdin();
let xs = stdin
.lock()
.lines()
.map(|ox| ox.unwrap().trim().to_string())
.flat_map(|s| str::parse::<f32>(&s))
.take(11)
.collect::<Vec<_>>();
for x in xs.into_iter().rev() {
match op(x) {
Some(y) => println!("{}", y),
None => println!("overflow"),
};
}
}

View file

@ -0,0 +1,26 @@
object TPKa extends App {
final val numbers = scala.collection.mutable.MutableList[Double]()
final val in = new java.util.Scanner(System.in)
while (numbers.length < CAPACITY) {
print("enter a number: ")
try {
numbers += in.nextDouble()
}
catch {
case _: Exception =>
in.next()
println("invalid input, try again")
}
}
numbers reverseMap { x =>
val fx = Math.pow(Math.abs(x), .5D) + 5D * (Math.pow(x, 3))
if (fx < THRESHOLD)
print("%8.3f -> %8.3f\n".format(x, fx))
else
print("%8.3f -> %s\n".format(x, Double.PositiveInfinity.toString))
}
private final val THRESHOLD = 400D
private final val CAPACITY = 11
}

View file

@ -0,0 +1,8 @@
var nums; do {
nums = Sys.readln("Please type 11 space-separated numbers: ").nums
} while(nums.len != 11)
nums.reverse.each { |n|
var r = (n.abs.sqrt + (5 * n**3));
say "#{n}\t#{ r > 400 ? 'Urk!' : r }";
}

View file

@ -0,0 +1,12 @@
10 DIM A(11)
20 PRINT "ENTER ELEVEN NUMBERS:"
30 FOR I=1 TO 11
40 INPUT A(I)
50 NEXT I
60 FOR I=11 TO 1 STEP -1
70 LET Y=SQR ABS A(I)+5*A(I)**3
80 IF Y<=400 THEN GOTO 110
90 PRINT A(I),"TOO LARGE"
100 GOTO 120
110 PRINT A(I),Y
120 NEXT I

View file

@ -0,0 +1,18 @@
import Foundation
print("Enter 11 numbers for the Trabb─Pardo─Knuth algorithm:")
let f: (Double) -> Double = { sqrt(fabs($0)) + 5 * pow($0, 3) }
(1...11)
.generate()
.map { i -> Double in
print("\(i): ", terminator: "")
guard let s = readLine(), let n = Double(s) else { return 0 }
return n
}
.reverse()
.forEach {
let result = f($0)
print("f(\($0))", result > 400.0 ? "OVERFLOW" : result, separator: "\t")
}

View file

@ -0,0 +1,37 @@
|Trabb PardoKnuth algorithm
a : 11 0
i
if i LE 10
[] $s
~ $s w
w a.i
+ i
goif
endif
10 i
if i GE 0
call f
if x GT 400
'too large' $s
else
~ x $s
endif
~ i $r
+ ' ' $r
+ $r $s.1
$s []
- i
goif
endif
stop
f a.i t
* t t x
* x t x
* 5 x
abs t
sqrt t y
+ y x
return

View file

@ -0,0 +1,20 @@
# Helper procedures
proc f {x} {expr {abs($x)**0.5 + 5*$x**3}}
proc overflow {y} {expr {$y > 400}}
# Read in 11 numbers, with nice prompting
fconfigure stdout -buffering none
for {set n 1} {$n <= 11} {incr n} {
puts -nonewline "number ${n}: "
lappend S [scan [gets stdin] "%f"]
}
# Process and print results in reverse order
foreach x [lreverse $S] {
set result [f $x]
if {[overflow $result]} {
puts "${x}: TOO LARGE!"
} else {
puts "${x}: $result"
}
}

View file

@ -0,0 +1,26 @@
FUNCTION f (n)
LET f = SQR(ABS(n)) + 5 * n ^ 3
END FUNCTION
DIM s(1 TO 11)
PRINT "enter 11 numbers"
FOR i = 1 TO 11
PRINT STR$(i); " => ";
INPUT s(i)
NEXT i
PRINT
PRINT "--------------------"
LET i = i - 1
DO
PRINT "f("; STR$(s(i)); ") = ";
LET x = f(s(i))
IF x > 400 THEN
PRINT "-=< overflow >=-"
ELSE
PRINT x
END IF
LET i = i - 1
LOOP UNTIL i < 1
END

View file

@ -0,0 +1,20 @@
Function tpk(s)
arr = Split(s," ")
For i = UBound(arr) To 0 Step -1
n = fx(CDbl(arr(i)))
If n > 400 Then
WScript.StdOut.WriteLine arr(i) & " = OVERFLOW"
Else
WScript.StdOut.WriteLine arr(i) & " = " & n
End If
Next
End Function
Function fx(x)
fx = Sqr(Abs(x))+5*x^3
End Function
'testing the function
WScript.StdOut.Write "Please enter a series of numbers:"
list = WScript.StdIn.ReadLine
tpk(list)

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