Content deleted Content added
→Ruby: Modified ruby version to make slightly more idiomatic |
No edit summary |
||
Line 40:
The problem with the usually specified function is that the term <code>5*t^3</code> gives overflows in almost all languages for very large negative values.
===[[Bash (Unix shell)|Bash]]===
The following works with and outputs (rounded-off) integers only:
<source lang="bash">
f() {
echo "sqrt(${1#-}) + 5 * $1 ^ 3" | bc
}
array=()
for i in {0..10}; do
read array[n]
done
for ((i=${#array[@]}-1; i>=0; --i)); do
let x=$(f ${array[$i]})
(( x > 400 )) && echo 'TOO LARGE' || echo $x
done
</source>
Although external programs can be used for unavailable (complex) functions, Bash is inherently incapable of floating-point arithmetic comparison.
===[[C (programming language) | C]]===
Line 84 ⟶ 106:
Haskell uses monads for input/output and the Maybe data type to signal overflow.
===[[
A [[Lua (programming language)|Lua]] variant might look like this. [[Lua (programming language)|Lua]] is compiled with [[Double precision]] numbers by default, but any other format is possible.
<!-- Coloring for Lua seems to be only minimal. -->
<source lang="lua">
function f(x)
return math.abs(x)^0.5 + 5*x^3
end
t = {}
for i=1,11 do
table.insert(t, io.read())
end
for i=#t,1,-1 do
if r > 400
then print("TOO LARGE")
else print(r)
end
end
</source>
Line 134 ⟶ 150:
let p x = x < 400.0 in
List.filter p (List.map f (List.rev l))
</source>
===[[Pascal_(programming_language)| Pascal]]===
<source lang="pascal">
program TrabbPardoKnuth;
function F(X : real) : real;
begin
F := Sqrt(Abs(X)) + 5 * X * X * X;
end;
const
N = 11;
var
Vals : array[1..N] of real;
I, X : integer;
begin
for I := 1 To N do
ReadLn(Vals[I]);
for I := N downto 1 do
begin
X := F(Vals[I]);
if X > 400 Then
WriteLn('Too Large!')
else
WriteLn(X);
end;
end;
</source>
Line 155 ⟶ 202:
</source>
===[[
<source lang="python">
import math
def f(x):
return math.sqrt(abs(x)) + 5 * x**3
vals = [float(raw_input()) for i in range(11)]
for i, x in enumerate(reversed(vals)):
y = f(x)
print('{0}: {1}'.format(i, y if y <= 400 else 'TOO LARGE'))
</source>
Floating point in Python on most platforms is [[IEEE-754]], which can return "nan" and "inf" values, or raise an appropriate Python exception.
===[[R (programming language)|R]]/[[S-PLUS]]===
Line 193 ⟶ 231:
The last implementation makes use of the lazy evaluation mechanism of R for default values of parameters: <code>t</code> is evaluated only the first time it is used in a computation, after which <code>t</code> is well defined.
===[[
The [[Ruby (programming language)|Ruby]] version takes advantage of some of its distinctive features:
<!-- Note that Ruby is not correctly colored by <source>. -->
<source lang="ruby">
def f(x)
Math.sqrt(x.abs) + 5*x ** 3
end
11.times.collect{ gets.to_i }.reverse.each do |x|
y = f(x)
puts "#{x} #{y.infinite? ? 'TOO LARGE' : y}"
end
</source>
===[[Scheme (programming language)|Scheme]]===
|