Real constants and functions
You are encouraged to solve this task according to the task description, using any language you may know.
- e (base of the natural logarithm)
- π
- square root
- logarithm (any base allowed)
- exponential (ex)
- absolute value (a.k.a. "magnitude")
- floor (largest integer less than or equal to this number--not the same as truncate or int)
- ceiling (smallest integer not less than this number--not the same as round up)
- power (xy)
See also Trigonometric Functions
[edit] ACL2
Only the last three are available as built in functions.
(floor 15 2) ;; This is the floor of 15/2
(ceiling 15 2)
(expt 15 2) ;; 15 squared
[edit] ActionScript
Actionscript has all the functions and constants mentioned in the task, available in the Math class.
Math.E; //e
Math.PI; //pi
Math.sqrt(u); //square root of u
Math.log(u); //natural logarithm of u
Math.exp(u); //e to the power of u
Math.abs(u); //absolute value of u
Math.floor(u);//floor of u
Math.ceil(u); //ceiling of u
Math.pow(u,v);//u to the power of v
The Math class also contains several other constants.
Math.LN10; // natural logarithm of 10
Math.LN2; // natural logarithm of 2
Math.LOG10E; // base-10 logarithm of e
Math.LOG2E; // base-2 logarithm of e
Math.SQRT1_2;// square root of 1/2
Math.SQRT2; //square root of 2
[edit] Ada
Most of the constants and functions used in this task are defined in the pre-defined Ada package Ada.Numerics.Elementary_Functions.
Ada.Numerics.e -- Euler's number
Ada.Numerics.pi -- pi
sqrt(x) -- square root
log(x, base) -- logarithm to any specified base
exp(x) -- exponential
abs(x) -- absolute value
S'floor(x) -- Produces the floor of an instance of subtype S
S'ceiling(x) -- Produces the ceiling of an instance of subtype S
x**y -- x raised to the y power
[edit] Aime
# e
exp(1);
# pi
2 * asin(1);
sqrt(x);
log(x);
exp(x);
fabs(x);
floor(x);
ceil(x);
pow(x, y);
[edit] ALGOL 68
REAL x:=exp(1), y:=4*atan(1);
printf(($g(-8,5)"; "$,
exp(1), # e #
pi, # pi #
sqrt(x), # square root #
log(x), # logarithm base 10 #
ln(x), # natural logarithm #
exp(x), # exponential #
ABS x, # absolute value #
ENTIER x, # floor #
-ENTIER -x, # ceiling #
x ** y # power #
))
Output:
2.71828; 3.14159; 1.64872; 0.43429; 1.00000; 15.15426; 2.71828; 2.00000; 3.00000; 23.14069;
ALGOL 68 also includes assorted long, short and complex versions of the above, eg: long exp, long long exp, short exp, complex exp etc.
And assorted trig functions: sin(x), arcsin(x), cos(x), arccos(x), tan(x), arctan(x), arctan2(x,y), sinh(x), arcsinh(x), cosh(x), arccosh(x), tanh(x) AND arctanh(x).
[edit] AutoHotkey
The following math functions are built into AutoHotkey:
Sqrt(Number) ; square root
Log(Number) ; returns logarithm (base 10)
Ln(Number) ; returns natural logarithm (base e)
Exp(N) ; returns e to the N power
Abs(Number) ; absolute value
Floor(Number) ; floor value
Ceil(Number) ; ceiling value
The following math operations are not built-in functions but can be performed using Autohotkey:
x**y ; x to the y power
pi() { ; will return pi when custom function is called
return 22/7
}
The following are additional trigonometric functions that are built into the Autohotkey language:
Sin(Number) ; sine
Cos(Number) ; cosine
Tan(Number) ; tangent
ASin(Number) ; arcsine
ACos(Number) ; arccosine
ATan(Number) ; arctangent
[edit] AWK
Awk has square root, logarithm, exponential and power.
BEGIN {
print sqrt(2) # square root
print log(2) # logarithm base e
print exp(2) # exponential
print 2 ^ -3.4 # power
}
# outputs 1.41421, 0.693147, 7.38906, 0.0947323
Power's note: With nawk or gawk,2 ** -3.4acts like2 ^ -3.4. With mawk,2 ** -3.4is a syntax error. Nawk allows**, but its manual page only has^. Gawk's manual warns, "The POSIX standard only specifies the use of `^' for exponentiation. For maximum portability, do not use the `**' operator."
Awk misses e, pi, absolute value, floor and ceiling; but these are all easy to implement.
BEGIN {
E = exp(1)
PI = atan2(0, -1)
}
function abs(x) {
return x < 0 ? -x : x
}
function floor(x) {
y = int(x)
return y > x ? y - 1 : y
}
function ceil(x) {
y = int(x)
return y < x ? y + 1 : y
}
BEGIN {
print E
print PI
print abs(-3.4) # absolute value
print floor(-3.4) # floor
print ceil(-3.4) # ceiling
}
# outputs 2.71828, 3.14159, 3.4, -4, -3
[edit] BASIC
ABS(x) 'absolute value
SQR(x) 'square root
EXP(x) 'exponential
LOG(x) 'natural logarithm
x ^ y 'power
'floor, ceiling, e, and pi not available
[edit] BBC BASIC
e = EXP(1)
Pi = PI
Sqr2 = SQR(2)
Ln2 = LN(2)
Log2 = LOG(2) : REM Base 10
Exp2 = EXP(2)
Abs2 = ABS(-2)
Floor = INT(1.234)
Ceil = FNceil(1.234)
Power = 1.23^4
END
DEF FNceil(n) = INT(n) - (INT(n) <> n)
[edit] bc
The language has square root and power, but power only works if the exponent is an integer.
scale = 6
sqrt(2) /* 1.414213 square root */
4.3 ^ -2 /* .054083 power (integer exponent) */
The standard library has natural logarithm and exponential functions. It can calculate e and pi: e comes from the exponential function, while pi is four times the arctangent of one. The usual formulas can calculate the powers with fractional exponents, and the logarithms with any base.
scale = 6
l(2) /* .693147 natural logarithm */
e(2) /* 7.389056 exponential */
p = 4 * a(1)
e = e(1)
p /* 3.141592 pi to 6 fractional digits */
e /* 2.178281 e to 6 fractional digits */
e(l(2) * -3.4) /* .094734 2 to the power of -3.4 */
l(1024) / l(2) /* 10.000001 logarithm base 2 of 1024 */
The missing functions are absolute value, floor and ceiling. You can implement these functions, if you know what to do.
/* absolute value */
define v(x) {
if (x < 0) return (-x)
return (x)
}
/* floor */
define f(x) {
auto s, y
s = scale
scale = 0
y = x / 1
scale = s
if (y > x) return (y - 1)
return (y)
}
/* ceiling */
define g(x) {
auto s, y
s = scale
scale = 0
y = x / 1
scale = s
if (y < x) return (y + 1)
return (y)
}
v(-3.4) /* 3.4 absolute value */
f(-3.4) /* -4 floor */
g(-3.4) /* -3 ceiling */
[edit] C
Most of the following functions take a double.
#include <math.h>
M_E; /* e - not standard but offered by most implementations */
M_PI; /* pi - not standard but offered by most implementations */
sqrt(x); /* square root--cube root also available in C99 (cbrt) */
log(x); /* natural logarithm--log base 10 also available (log10) */
exp(x); /* exponential */
abs(x); /* absolute value (for integers) */
fabs(x); /* absolute value (for doubles) */
floor(x); /* floor */
ceil(x); /* ceiling */
pow(x,y); /* power */
To access the M_PI, etc. constants in Visual Studio, you may need to add the line #define _USE_MATH_DEFINES before the #include <math.h>.
[edit] C++
#include <iostream>
#include <cmath>
#ifdef M_E
static double euler_e = M_E;
#else
static double euler_e = std::exp(1); // standard fallback
#endif
#ifdef M_PI
static double pi = M_PI;
#else
static double pi = std::acos(-1);
#endif
int main()
{
std::cout << "e = " << euler_e
<< "\npi = " << pi
<< "\nsqrt(2) = " << std::sqrt(2.0)
<< "\nln(e) = " << std::log(e)
<< "\nlg(100) = " << std::log10(100.0)
<< "\nexp(3) = " << std::exp(3.0)
<< "\n|-4.5| = " << std::abs(-4.5) // or std::fabs(4.0); both work in C++
<< "\nfloor(4.5) = " << std::floor(4.5)
<< "\nceiling(4.5) = " << std::ceil(4.5)
<< "\npi^2 = " << std::pow(pi,2.0) << std::endl;
}
[edit] C#
using System;
class Program {
static void Main(string[] args) {
Console.WriteLine(Math.E); //E
Console.WriteLine(Math.PI); //PI
Console.WriteLine(Math.Sqrt(10)); //Square Root
Console.WriteLine(Math.Log(10)); // Logarithm
Console.WriteLine(Math.Log10(10)); // Base 10 Logarithm
Console.WriteLine(Math.Exp(10)); // Exponential
Console.WriteLine(Math.Abs(10)); //Absolute value
Console.WriteLine(Math.Floor(10.0)); //Floor
Console.WriteLine(Math.Ceiling(10.0)); //Ceiling
Console.WriteLine(Math.Pow(2, 5)); // Exponentiation
}
}
[edit] Chef
See Basic integer arithmetic#Chef for powers.
[edit] Clojure
which is directly available.(Math/E); //e
(Math/PI); //pi
(Math/sqrt x); //square root--cube root also available (cbrt)
(Math/log x); //natural logarithm--log base 10 also available (log10)
(Math/exp x); //exponential
(Math/abs x); //absolute value
(Math/floor x); //floor
(Math/ceil x); //ceiling
(Math/pow x y); //power
Clojure does provide arbitrary precision versions as well:
(ns user (:require [clojure.contrib.math :as math]))
(math/sqrt x)
(math/abs x)
(math/floor x)
(math/ceil x)
(math/expt x y)
.. and as multimethods that can be defined for any type (e.g. complex numbers).
(ns user (:require [clojure.contrib.generic.math-functions :as generic]))
(generic/sqrt x)
(generic/log x)
(generic/exp x)
(generic/abs x)
(generic/floor x)
(generic/ceil x)
(generic/pow x y)
[edit] Common Lisp
In Lisp we should really be talking about numbers rather than the type real. The types real and complex are subtypes of number. Math operations that accept or produce complex numbers generally do.
(exp 1) ; e (Euler's number)
pi ; pi constant
(sqrt x) ; square root: works for negative reals and complex
(log x) ; natural logarithm: works for negative reals and complex
(log x 10) ; logarithm base 10
(exp x) ; exponential
(abs x) ; absolute value: result exact if input exact: (abs -1/3) -> 1/3.
(floor x) ; floor: restricted to real, two valued (second value gives residue)
(ceiling x) ; ceiling: restricted to real, two valued (second value gives residue)
(expt x y) ; power
[edit] D
import std.math ; // need to import this module
E // Euler's number
PI // pi constant
sqrt(x) // square root
log(x) // natural logarithm
log10(x) // logarithm base 10
log2(x) // logarithm base 2
exp(x) // exponential
abs(x) // absolute value (= magnitude for complex)
floor(x) // floor
ceil(x) // ceiling
pow(x,y) // power
[edit] Delphi
Log, Floor, Ceil and Power functions defined in Math.pas.
Exp(1); // e (Euler's number)
Pi; // π (Pi)
Sqrt(x); // square root
LogN(BASE, x) // log of x for a specified base
Log2(x) // log of x for base 2
Log10(x) // log of x for base 10
Ln(x); // natural logarithm (for good measure)
Exp(x); // exponential
Abs(x); // absolute value (a.k.a. "magnitude")
Floor(x); // floor
Ceil(x); // ceiling
Power(x, y); // power
[edit] DWScript
See Delphi.
[edit] E
? 1.0.exp()
# value: 2.7182818284590455
? 0.0.acos() * 2
# value: 3.141592653589793
? 2.0.sqrt()
# value: 1.4142135623730951
? 2.0.log()
# value: 0.6931471805599453
? 5.0.exp()
# value: 148.4131591025766
? (-5).abs()
# value: 5
? 1.2.floor()
# value: 1
? 1.2.ceil()
# value: 2
? 10 ** 6
# value: 1000000
[edit] Erlang
% Implemented by Arjun Sunel
-module(math_constants).
-export([main/0]).
main() ->
io:format("~p~n", [math:exp(1)] ), % e
io:format("~p~n", [math:pi()] ), % pi
io:format("~p~n", [math:sqrt(16)] ), % square root
io:format("~p~n", [math:log(10)] ), % natural logarithm
io:format("~p~n", [math:log10(10)] ), % base 10 logarithm
io:format("~p~n", [math:exp(2)] ), % e raised to the power of x
io:format("~p~n", [abs(-2.24)] ), % absolute value
io:format("~p~n", [floor(3.1423)] ), % floor
io:format("~p~n", [ceil(20.125)] ), % ceiling
io:format("~p~n", [math:pow(3,2)] ). % exponentiation
floor(X) when X < 0 ->
T = trunc(X),
case X - T == 0 of
true -> T;
false -> T - 1
end;
floor(X) ->
trunc(X).
ceil(X) when X < 0 ->
trunc(X);
ceil(X) ->
T = trunc(X),
case X - T == 0 of
true -> T;
false -> T + 1
end.
- Output:
2.718281828459045 3.141592653589793 4.0 2.302585092994046 1.0 7.38905609893065 2.24 3 21 9.0 ok
[edit] Factor
e ! e
pi ! π
sqrt ! square root
log ! natural logarithm
exp ! exponentiation
abs ! absolute value
floor ! greatest whole number smaller than or equal
ceiling ! smallest whole number greater than or equal
truncate ! remove the fractional part (i.e. round towards 0)
round ! round to next whole number
^ ! power
[edit] Fantom
The Float class holds 64-bit floating point numbers, and contains most of the useful mathematical functions. A floating point number must be specified when entered with the suffix 'f', e.g. 9f
Float.e
Float.pi
9f.sqrt
9f.log // natural logarithm
9f.log10 // logarithm to base 10
9f.exp // exponentiation
(-3f).abs // absolute value, note bracket
3.2f.floor // nearest Int smaller than this number
3.2f.ceil // nearest Int bigger than this number
3.2f.round // nearest Int
3f.pow(2f) // power
Note, . binds more tightly than -, so use brackets around negative numbers:
> -3f.pow(2f) -9 > (-3f).pow(2f) 9
[edit] Forth
1e fexp fconstant e
0e facos 2e f* fconstant pi \ predefined in gforth
fsqrt ( f -- f )
fln ( f -- f ) \ flog for base 10
fexp ( f -- f )
fabs ( f -- f )
floor ( f -- f ) \ round towards -inf
: ceil ( f -- f ) fnegate floor fnegate ; \ not standard, though fround is available
f** ( f e -- f^e )
[edit] Fortran
e ! Not available. Can be calculated EXP(1)
pi ! Not available. Can be calculated 4.0*ATAN(1.0)
SQRT(x) ! square root
LOG(x) ! natural logarithm
LOG10(x) ! logarithm to base 10
EXP(x) ! exponential
ABS(x) ! absolute value
FLOOR(x) ! floor - Fortran 90 or later only
CEILING(x) ! ceiling - Fortran 90 or later only
x**y ! x raised to the y power
[edit] Go
import "math"
// e and pi defined as constants.
// In Go, that means they are not of a specific data type and can be used as float32 or float64.
math.E
math.Pi
// The following functions all take and return the float64 data type.
math.Sqrt(x) // square root--cube root also available (math.Cbrt)
// natural logarithm--log base 10, 2 also available (math.Log10, math.Log2)
// also available is log1p, the log of 1+x. It is more accurate when x is near zero.
math.Log(x)
math.Exp(x) // exponential--exp base 10, 2 also available (math.Pow10, math.Exp2)
math.Abs(x) // absolute value
math.Floor(x) // floor
math.Ceil(x) // ceiling
math.Pow(x,y) // power
[edit] Groovy
Math constants and functions are as outlined in the Java example, except as follows:
Absolute Value
In addition to the java.lang.Math.abs() method, each numeric type has an abs() method, which can be invoked directly on the number:
println ((-22).abs())
Output:
22
Power
In addition to the java.lang.Math.pow() method, each numeric type works with the power operator (**), which can be invoked as an in-fix operator between two numbers:
println 22**3.5
Output:
49943.547010599876
Power results are not defined for all possible pairs of operands. Any power operation that does not have a result returns a 64-bit IEEE NaN (Not a Number) value.
println ((-22)**3.5)
Output:
NaN
Also note that at the moment (07:00, 19 March 2011 (UTC)) Groovy (1.7.7) gives a mathematically incorrect result for "0**0". The correct result should be "NaN", but the Groovy operation result is "1".
[edit] Haskell
The operations are defined for the various numeric typeclasses, as defined in their type signature.
exp 1 -- Euler number
pi -- pi
sqrt x -- square root
log x -- natural logarithm
exp x -- exponential
abs x -- absolute value
floor x -- floor
ceiling x -- ceiling
x ** y -- power (e.g. floating-point exponentiation)
x ^ y -- power (e.g. integer exponentiation, nonnegative y only)
x ^^ y -- power (e.g. integer exponentiation of rationals, also negative y)
[edit] HicEst
Except for x^y, this is identical to Fortran:
e ! Not available. Can be calculated EXP(1)
pi ! Not available. Can be calculated 4.0*ATAN(1.0)
x^0.5 ! square root
LOG(x) ! natural logarithm
LOG(x, 10) ! logarithm to base 10
EXP(x) ! exponential
ABS(x) ! absolute value
FLOOR(x) ! floor
CEILING(x) ! ceiling
x**y ! x raised to the y power
x^y ! same as x**y
[edit] Icon and Unicon
link numbers # for floor and ceil
procedure main()
write("e=",&e)
write("pi=",&pi)
write("phi=",&phi)
write("sqrt(2)=",sqrt(2.0))
write("log(e)=",log(&e))
write("log(100.,10)=",log(100,10))
write("exp(1)=",exp(1.0))
write("abs(-2)=",abs(-2))
write("floor(-2.2)=",floor(-2.2))
write("ceil(-2.2)=",ceil(-2.2))
write("power: 3^3=",3^3)
end
numbers provides floor and ceiling
Sample output:
e=2.718281828459045 pi=3.141592653589793 phi=1.618033988749895 sqrt(2)=1.414213562373095 log(e)=1.0 log(100.,10)=2.0 exp(1)=2.718281828459045 abs(-2)=2 floor(-2.2)=-2 ceil(-2.2)=-3
[edit] J
The examples below require arguments (x and y) to be numeric nouns.
e =. 1x1 NB. Euler's number, specified as a numeric literal.
e =. ^ 1 NB. Euler's number, computed by exponentiation.
pi=. 1p1 NB. pi, specified as a numeric literal.
pi=. o.1 NB. pi, computed trigonometrically.
magnitude_of_x =. |x
floor_of_x =. <.x
ceiling_of_x =. >.x
natural_log_of_x =. ^.x
base_x_log_of_y =. x^.y
x_squared =. *:x NB. special form
x_squared =. x^2 NB. exponential form
square_root_of_x =. %:x NB. special form
square_root_of_x =. x^0.5 NB. exponential form
x_to_the_y_power =. x^y
[edit] Java
All of these functions are in Java's Math class which, does not require any imports:
Math.E; //e
Math.PI; //pi
Math.sqrt(x); //square root--cube root also available (cbrt)
Math.log(x); //natural logarithm--log base 10 also available (log10)
Math.exp(x); //exponential
Math.abs(x); //absolute value
Math.floor(x); //floor
Math.ceil(x); //ceiling
Math.pow(x,y); //power
[edit] JavaScript
Math.E
Math.PI
Math.sqrt(x)
Math.log(x)
Math.exp(x)
Math.abs(x)
Math.floor(x)
Math.ceil(x)
Math.pow(x,y)
[edit] Liberty BASIC
Ceiling and floor easily implemented as functions.
sqr( is the LB function for square root.
e & pi not available- calculate as shown.
print exp( 1) ' e not available
print 4 *atn( 1) ' pi not available
x =12.345: y =1.23
print sqr( x), x^0.5 ' square root- NB the unusual name
print log( x) ' natural logarithm base e
print log( x) /2.303 ' base 10 logarithm
print log( x) /log( y) ' arbitrary base logarithm
print exp( x) ' exponential
print abs( x) ' absolute value
print floor( x) ' floor
print ceiling( x) ' ceiling
print x^y ' power
end
function floor( x)
if x >0 then
floor =int( x)
else
if x <>int( x) then floor =int( x) -1 else floor =int( x)
end if
end function
function ceiling( x)
if x <0 then
ceiling =int( x)
else
ceiling =int( x) +1
end if
end function
[edit] Logo
make "e exp 1
make "pi 2*(RADARCTAN 0 1)
sqrt :x
ln :x
exp :x
; there is no standard abs, floor, or ceiling; only INT and ROUND.
power :x :y
[edit] Lua
math.exp(1)
math.pi
math.sqrt(x)
math.log(x)
math.log10(x)
math.exp(x)
math.abs(x)
math.floor(x)
math.ceil(x)
x^y
[edit] Maple
> abs(ceil(floor(ln(exp(1)^sqrt(exp(Pi*I)+1)))));
0
[edit] Mathematica
E
Pi
Sqrt[x]
Log[x]
Log[b,x]
Exp[x]
Abs[x]
Floor[x]
Ceiling[x]
Power[x, y]
Where x is the number, and b the base. Exp[x] can also be inputted as E^x or Ex and Power[x,y] can be also inputted as x^y or xy. All functions work with symbols, integers, floats and can be complex. Abs giving the modulus (|x|) if the argument is a complex number. Constant like E and Pi are kep unevaluated until someone explicitly tells it to give a numerical approximation: N[Pi,n] gives Pi to n-digit precision. Functions given an exact argument will be kept unevaluated if the answer can't be written more compact, approximate arguments will always be evaluated:
Log[1.23] => 0.207014
Log[10] => Log[10]
Log[10,100] => 2
Log[E^4] => 4
Log[1 + I] => Log[1+I]
Log[1. + I] => 0.346574 + 0.785398 I
Ceiling[Pi] => 4
Floor[Pi] => 3
Sqrt[2] => Sqrt[2]
Sqrt[4] => 2
Sqrt[9/2] => 3/Sqrt[2]
Sqrt[3.5] => 1.87083
Sqrt[-5 + 12 I] => 2 + 3 I
Sqrt[-4] => 2I
Exp[2] => E^2
Exp[Log[4]] => 4
[edit] MAXScript
e -- Euler's number
pi -- pi
log x -- natural logarithm
log10 x -- log base 10
exp x -- exponantial
abs x -- absolute value
floor x -- floor
ceil x -- ceiling
pow x y -- power
[edit] Mercury
math.pi % Pi.
math.e % Euler's number.
math.sqrt(X) % Square root of X.
math.ln(X) % Natural logarithm of X.
math.log10(X) % Logarithm to the base 10 of X.
math.log2(X) % Logarithm to the base 2 of X.
math.log(B, X) % Logarithm to the base B of X.
math.exp(X) % e raised to the power of X.
float.abs(X) % Absolute value of X.
math.floor(X) % Floor of X.
math.ceiling(X) % Ceiling of X.
math.pow(X, Y) % X raised to the power of Y.
[edit] Metafont
show mexp(256); % outputs e; since MF uses mexp(x) = exp(x/256)
show 3.14159; % no pi constant built in; of course we can define it
% in several ways... even computing
% C/2r (which would be funny since MF handles paths,
% and a circle is a path...)
show sqrt2; % 1.41422, or in general sqrt(a)
show mexp(256*x); % see e.
show abs(x); % returns |x| (the absolute value of the number x, or
% the length of the vector x); it is the same as
% length(x); plain Metafont in fact says:
% let abs = length;
show floor(x); % floor
show ceiling(x); % ceiling
show x**y; % ** is not a built in: it is defined in the basic macros
% set for Metafont (plain Metafont) as a primarydef
[edit] МК-61/52
1 e^x С/П
пи С/П
КвКор С/П
lg С/П
e^x С/П
|x| С/П
П0 ^ [x] П1 - x=0 09 ИП0 С/П ЗН
x>=0 14 ИП1 С/П ИП1 1 - С/П
П0 ^ [x] П1 - x=0 09 ИП0 С/П ЗН
x<0 14 ИП1 С/П ИП1 1 + С/П
x^y С/П
[edit] Modula-3
Modula-3 uses a module that is a wrapper around C's math.h.
Note that all of these procedures (except the built ins) take LONGREALs as their argument, and return LONGREALs.
Math.E;
Math.Pi;
Math.sqrt(x);
Math.log(x);
Math.exp(x);
ABS(x); (* Built in function. *)
FLOOR(x); (* Built in function. *)
CEILING(x); (* Built in function. *)
Math.pow(x, y);
[edit] NetRexx
All the required constants and functions (and more) are in Java's Math class. NetRexx also provides a limited set of built in numeric manipulation functions for it's Rexx object.
/* NetRexx */
options replace format comments java crossref symbols nobinary utf8
numeric digits 30
x = 2.5
y = 3
pad = 40
say
say 'Java Math constants & functions:'
say Rexx(' Euler''s number (e):').left(pad) Math.E
say Rexx(' Pi:').left(pad) Math.PI
say Rexx(' Square root of' x':').left(pad) Math.sqrt(x)
say Rexx(' Log(e) of' x':').left(pad) Math.log(x)
say Rexx(' Log(e) of e:').left(pad) Math.log(Math.E)
say Rexx(' Log(10) of' x':').left(pad) Math.log10(x)
say Rexx(' Log(10) of 10:').left(pad) Math.log10(10)
say Rexx(' Exponential (e**x) of' x':').left(pad) Math.exp(x)
say Rexx(' Exponential (e**x) of log(e)' x':').left(pad) Math.exp(Math.log(x))
say Rexx(' Abs of' x':').left(pad) Math.abs(x.todouble)
say Rexx(' Abs of' (-x)':').left(pad) Math.abs((-x).todouble)
say Rexx(' Floor of' x':').left(pad) Math.floor(x)
say Rexx(' Floor of' (-x)':').left(pad) Math.floor((-x))
say Rexx(' Ceiling of' x':').left(pad) Math.ceil(x)
say Rexx(' Ceiling of' (-x)':').left(pad) Math.ceil((-x))
say Rexx(' ' x 'to the power of' y':').left(pad) Math.pow(x, y)
say Rexx(' ' x 'to the power of' 1 / y':').left(pad) Math.pow(x, 1 / y)
say Rexx(' 10 to the power of log10' x':').left(pad) Math.pow(10, Math.log10(x))
-- Extras
say Rexx(' Cube root of' x':').left(pad) Math.cbrt(x)
say Rexx(' Hypotenuse of' 3 'x' 4 'right triangle:').left(pad) Math.hypot(3, 4)
say Rexx(' Max of' (-x) '&' x':').left(pad) Math.max((-x).todouble, x)
say Rexx(' Min of' (-x) '&' x':').left(pad) Math.min((-x).todouble, x)
say Rexx(' Signum of' x':').left(pad) Math.signum((x).todouble)
say Rexx(' Signum of' x '-' x':').left(pad) Math.signum((x - x).todouble)
say Rexx(' Signum of' (-x)':').left(pad) Math.signum((-x).todouble)
say
say 'NetRexx built-in support for numeric data:'
say Rexx(' Abs of' x':').left(pad) x.abs()
say Rexx(' Abs of' (-x)':').left(pad) (-x).abs()
say Rexx(' Sign of' x':').left(pad) x.sign()
say Rexx(' Sign of' x '-' x':').left(pad) (x - x).sign()
say Rexx(' Sign of' (-x)':').left(pad) (-x).sign()
say Rexx(' Max of' (-x) '&' x':').left(pad) (-x).max(x)
say Rexx(' Min of' (-x) '&' x':').left(pad) (-x).min(x)
say Rexx(' Truncate' x 'by' y':').left(pad) x.trunc(y)
say Rexx(' Format (with rounding)' x 'by' y':').left(pad) x.format(y, 0)
Output:
Java Math constants & functions: Euler's number (e): 2.718281828459045 Pi: 3.141592653589793 Square root of 2.5: 1.58113883008419 Log(e) of 2.5: 0.9162907318741551 Log(e) of e: 1 Log(10) of 2.5: 0.3979400086720376 Log(10) of 10: 1 Exponential (e**x) of 2.5: 12.18249396070347 Exponential (e**x) of log(e) 2.5: 2.5 Abs of 2.5: 2.5 Abs of -2.5: 2.5 Floor of 2.5: 2 Floor of -2.5: -3 Ceiling of 2.5: 3 Ceiling of -2.5: -2 2.5 to the power of 3: 15.625 2.5 to the power of 0.3333333333333333 1.357208808297453 10 to the power of log10 2.5: 2.5 Cube root of 2.5: 1.357208808297453 Hypotenuse of 3 x 4 right triangle: 5 Max of -2.5 & 2.5: 2.5 Min of -2.5 & 2.5: -2.5 Signum of 2.5: 1 Signum of 2.5 - 2.5: 0 Signum of -2.5: -1 NetRexx built-in support for numeric data: Abs of 2.5: 2.5 Abs of -2.5: 2.5 Sign of 2.5: 1 Sign of 2.5 - 2.5: 0 Sign of -2.5: -1 Max of -2.5 & 2.5: 2.5 Min of -2.5 & 2.5: -2.5 Truncate 2.5 by 3: 2.500 Format (with rounding) 2.5 by 3: 3
[edit] Objeck
Float->Pi();
Float->E();
4.0->SquareRoot();
1.5->Log();
# exponential is not supported
3.99->Abs();
3.99->Floor();
3.99->Ceiling();
4.5->Ceiling(2.0);
[edit] OCaml
Unless otherwise noted, the following functions are for floats only:
sqrt x (* square root *)
log x (* natural logarithm--log base 10 also available (log10) *)
exp x (* exponential *)
abs_float x (* absolute value *)
abs x (* absolute value (for integers) *)
floor x (* floor *)
ceil x (* ceiling *)
x ** y (* power *)
-. x (* negation for floats *)
[edit] Octave
e % e
pi % pi
sqrt(pi) % square root
log(e) % natural logarithm
exp(pi) % exponential
abs(-e) % absolute value
floor(pi) % floor
ceil(pi) % ceiling
e**pi % power
[edit] Oz
{ForAll
[
{Exp 1.} %% 2.7183 Euler's number: not predefined
4. * {Atan2 1. 1.} %% 3.1416 pi: not predefined
{Sqrt 81.} %% 9.0 square root; expects a float
{Log 2.7183} %% 1.0 natural logarithm
{Abs ~1} %% 1 absolute value; expects a float or an integer
{Floor 1.999} %% 1.0 floor; expects and returns a float
{Ceil 1.999} %% 2.0 ceiling; expects and returns a float
{Pow 2 3} %% 8 power; both arguments must be of the same type
]
Show}
[edit] PARI/GP
[exp(1), Pi, sqrt(2), log(2), abs(2), floor(2), ceil(2), 2^3]
[edit] Pascal
See Delphi
[edit] Perl
use POSIX; # for floor() and ceil()
exp(1); # e
4 * atan2(1, 1); # pi
sqrt($x); # square root
log($x); # natural logarithm; log10() available in POSIX module
exp($x); # exponential
abs($x); # absolute value
floor($x); # floor
ceil($x); # ceiling
$x ** $y; # power
[edit] Perl 6
say e; # e
say pi; # pi
say sqrt 2; # Square root
say log 2; # Natural logarithm
say exp 42; # Exponentiation base e
say abs -2; # Absolute value
say floor pi; # Floor
say ceiling pi; # Ceiling
say 4**7; # Exponentiation
[edit] PHP
M_E; //e
M_PI; //pi
sqrt(x); //square root
log(x); //natural logarithm--log base 10 also available (log10)
exp(x); //exponential
abs(x); //absolute value
floor(x); //floor
ceil(x); //ceiling
pow(x,y); //power
[edit] PL/I
/* e not available other than by using exp(1q0).*/
/* pi not available other than by using a trig function such as atan */
y = sqrt(x);
y = log(x);
y = log2(x);
y = log10(x);
y = exp(x);
y = abs(x);
y = floor(x);
y = ceil(x);
a = x**y; /* power */
/* extra functions: */
y = erf(x); /* the error function. */
y = erfc(x); /* the error function complemented. */
y = gamma (x);
y = loggamma (x);
[edit] PicoLisp
PicoLisp has only limited floating point support (scaled bignum arithmetics). It can handle real numbers with as many positions after the decimal point as desired, but is practically limited by the precision of the C-library functions (about 16 digits). The default precision is six, and can be changed with 'scl':
(scl 12) # 12 places after decimal point
(load "@lib/math.l")
(prinl (format (exp 1.0) *Scl)) # e, exp
(prinl (format pi *Scl)) # pi
(prinl (format (pow 2.0 0.5) *Scl)) # sqare root
(prinl (format (sqrt (* 2.0 1.0)) *Scl))
(prinl (format (log 2.0) *Scl)) # logarithm
(prinl (format (exp 4.0) *Scl)) # exponential
(prinl (format (abs -7.2) *Scl)) # absolute value
(prinl (abs -123))
(prinl (format (pow 3.0 4.0) *Scl)) # power
Output:
2.718281828459 3.141592653590 1.414213562373 1.414213562373 0.693147180560 54.598150033144 7.200000000000 123 81.000000000000
[edit] Pop11
pi ;;; Number Pi
sqrt(x) ;;; Square root
log(x) ;;; Natural logarithm
exp(x) ;;; Exponential function
abs(x) ;;; Absolute value
x ** y ;;; x to the power y
The number e is not provided directly, one has to compute 'exp(1)' instead. Also, f/math>)
See also Trigonometric Functions
[edit] ACL2
Only the last three are available as built in functions.
loor and ceiling are not provided, one can define them using integer part:
define floor(x);
if x < 0 then
-intof(x);
else
intof(x);
endif;
enddefine;
define ceiling(x);
-floor(-x);
enddefine;
[edit] PowerShell
Since PowerShell has access to .NET all this can be achieved using the .NET Base Class Library:
Write-Host ([Math]::E)
Write-Host ([Math]::Pi)
Write-Host ([Math]::Sqrt(2))
Write-Host ([Math]::Log(2))
Write-Host ([Math]::Exp(2))
Write-Host ([Math]::Abs(-2))
Write-Host ([Math]::Floor(3.14))
Write-Host ([Math]::Ceiling(3.14))
Write-Host ([Math]::Pow(2, 3))
[edit] PureBasic
Debug #E
Debug #PI
Debug Sqr(f)
Debug Log(f)
Debug Exp(f)
Debug Log10(f)
Debug Abs(f)
Debug Pow(f,f)
[edit] Python
import math
math.e # e
math.pi # pi
math.sqrt(x) # square root (Also commonly seen as x ** 0.5 to obviate importing the math module)
math.log(x) # natural logarithm
math.log10(x) # base 10 logarithm
math.exp(x) # e raised to the power of x
abs(x) # absolute value
math.floor(x) # floor
math.ceil(x) # ceiling
x ** y # exponentiation
pow(x, y[, n]) # exponentiation [, modulo n (useful in certain encryption/decryption algorithms)]
# The math module constants and functions can, of course, be imported directly by:
# from math import e, pi, sqrt, log, log10, exp, floor, ceil
[edit] R
exp(1) # e
pi # pi
sqrt(x) # square root
log(x) # natural logarithm
log10(x) # base 10 logarithm
log(x, y) # arbitrary base logarithm
exp(x) # exponential
abs(x) # absolute value
floor(x) # floor
ceiling(x) # ceiling
x^y # power
[edit] Racket
(exp 1) ; e
pi ; pi
(sqrt x) ; square root
(log x) ; natural logarithm
(exp x) ; exponential
(abs x) ; absolute value
(floor x) ; floor
(ceiling x) ; ceiling
(expt x y) ; power
[edit] REXX
REXX has no built-in functions for trig functions, square root, pi, exponential (e raised to a power), logrithms and other similar functions.
REXX doesn't have any built-in (math) constants.
a=abs(y) /*takes the absolute value of y.*/
r=x**y /*only supports integer powers. */
[edit] CEILING
A ceiling function for REXX:
ceiling: procedure; parse arg x; t=trunc(x); return t+(x>0)*(x\=t)
[edit] FLOOR
A floor function for REXX:
floor: procedure; parse arg x; t=trunc(x); return t-(x<0)-(x\=t)
[edit] SQRT (square root)
A [principal] square root (SQRT) function for REXX (arbitrary precision):
/*─────────────────────────────────────SQRT subroutine──────────────────*/
sqrt: procedure /*square root subroutine. */
/*returns the principal SQRT. */
r='' /*list of square roots calculated*/
do j=1 for arg() /*process each argument specified*/
a=arg(j) /*extract the argument specified*/
do k=1 for words(a) /*process each number specified. */
r=r sqrt_(word(a,k)) /*calculate sqrt, add to results.*/
end
end
return space(r) /*return list of SQRTs calculated*/
/*─────────────────────────────────────SQRT_ subroutine─────────────────*/
sqrt_: procedure; parse arg x 1 ox
if x=0 then return 0 /*handle special case of zero. */
if x='' then return '' /*if null, then return null. */
if pos(',',x)\==0 then do;x=space(translate(x,,","),0);ox=x;end /*del ,*/
if \datatype(x,'N') then return '[n/a]' /*not numberic? not applicable*/
x=abs(x) /*just use positive value of X. */
d=digits() /*get the current precision. */
numeric digits 11 /*use "small" precision at first.*/
g=sqrt_guess() /*try get a good 1st guesstimate.*/
m.=11 /*technique uses just enough digs*/
p=d+d%4+2 /*# of iterations (calculations).*/
/*Note: to insure enough accuracy*/
/*for the result, the precsion */
/*during the SQRT calcuations is */
/*increased by two extra digits. */
do j=0 while p>9
m.j=p
p=p%2+1
end
do k=j+5 to 0 by -1
if m.k>11 then numeric digits m.k /*each iteration, increase digits*/
g=.5*(g+x/g) /*do the nitty-gritty calculation*/
end /* .5* is faster than /2 */
numeric digits d /*restore the original precision.*/
return (g/1)left('i',ox<0) /*normalize to old digs, complex?*/
sqrt_guess: numeric form scientific /*force scientific form of number*/
parse value format(x,2,1,,0) 'E0' with g 'E' _ . /*get X's exponent.*/
return g*.5'E'_%2 /*1st guesstimate. */
/*┌────────────────────────────────────────────────────────────────────┐
┌─┘ √ └─┐
│ While the above REXX code seems like it's doing a lot of extra work, │
│ it saves a substanial amount of processing time when the precision │
│ (DIGITs) is a lot greater than the default (9 digits). │
│ │
│ Indeed, when computing square roots in the hundreds (even thousands) │
│ of digits, this technique reduces the amount of CPU processing time │
│ by keeping the length of the computations to a minimim (due to a large │
│ precision) while the accuracy (at the beginning) isn't important for │
│ caculating the guesstimate (the running square root guess). │
└─┐ √ ┌─┘
└────────────────────────────────────────────────────────────────────┘*/
[edit] SQRT (simple version)
/*─────────────────────────────────────SQRT subroutine──────────────────*/
sqrt: procedure; parse arg x /*a simple SQRT subroutine. */
if x=0 then return 0 /*handle special case of zero. */
d=digits() /*get the current precision. */
numeric digits digits()+2 /*ensure extra precision. */
g=x/4 /*try get a so-so 1st guesstimate*/
old=0 /*set OLD guess to zero. */
do forever
g=.5*(g+x/g) /*do the nitty-gritty calculation*/
if g=old then leave /*if G is the same as old, quit. */
old=g /*save OLD for next iteration. */
end /* .5* is faster than /2 */
numeric digits d /*restore the original precision.*/
return g/1 /*normalize to old precision. */
[edit] other
Other mathetical-type functions supported are:
numeric digits ddd /*sets the current precision to DDD */
numeric fuzz fff /*arithmetic comparisons with FFF fuzzy*/
numeric form kkk /*exponential: scientific | engineering*/
low=min(a,b,c,d,e,f,g, ...) /*finds the min of specified arguments.*/
big=min(a,b,c,d,e,f,g, ...) /*finds the max of specified arguments.*/
rrr=random(low,high) /*gets a random integer from LOW-->HIGH*/
arr=random(low,high,seed) /* ... with a seed (to make repeatable)*/
mzp=sign(x) /*finds the sign of x (-1, 0, +1). */
fs=format(x) /*formats X with the current DIGITS() */
fb=format(x,bbb) /* BBB digs before decimal*/
fa=format(x,bbb,aaa) /* AAA digs after decimal*/
fa=format(x,,0) /* rounds X to an integer.*/
fe=format(x,,eee) /* exponent has eee places. */
ft=format(x,,eee,ttt) /*if x exceeds TTT digits, force exp. */
hh=b2x(bbb) /*converts binary/bits to hexadecimal. */
dd=c2d(ccc) /*converts character to decimal. */
hh=c2x(ccc) /*converts character to hexadecimal. */
cc=d2c(ddd) /*converts decimal to character. */
hh=d2x(ddd) /*converts decimal to hexadecimal. */
bb=x2b(hhh) /*converts hexadecimal to binary (bits)*/
cc=x2c(hhh) /*converts hexadecimal to character. */
dd=x2d(hhh) /*converts hexadecimal to decimal. */
[edit] RLaB
[edit] Mathematical Constants
RLaB has a number of mathematical constants built-in within the list const. These facilities are provided through the Gnu Science Library [[1]].
>> const
e euler ln10 ln2 lnpi
log10e log2e pi pihalf piquarter
rpi sqrt2 sqrt2r sqrt3 sqrtpi
tworpi
[edit] Physical Constants
Another list of physical constants and unit conversion factors exists and is called mks. Here the conversion goes between that particular unit and the equivalent unit in, one and only, metric system.
>> mks
F G J L N
Na R0 Ry Tsp V0
a a0 acre alpha atm
au bar barn btu c
cal cgal cm cm2 cm3
ct cup curie day dm
dm2 dm3 dyne e eV
eps0 erg fathom floz ft
ftcan ftlam g gal gauss
gf h ha hbar hour
hp in inH2O inHg kSB
kb kcal km km2 km3
kmh knot kpf lam lb
lumen lux ly mHg mSun
me micron mil mile min
mm mm2 mm3 mmu mn
mp mph mu0 mub mue
mun mup nmi oz pal
parsec pf phot poise psi
rad roe stilb stokes tcs
therm tntton ton torr toz
tsp uam ukgal ukton uston
week yd
[edit] Elementary Functions
>> x = rand()
>> sqrt(x)
2.23606798
>> log(x)
1.60943791
>> log10(x)
0.698970004
>> exp(x)
148.413159
>> abs(x)
5
>> floor(x)
5
>> ceil(x)
5
>> x .^ 2
25
[edit] Ruby
Math::E #e
Math::PI #pi
Math.sqrt(x) #square root
Math.log(x) #natural logarithm
Math.log10(x) #base 10 logarithm
Math.exp(x) #exponential
x.abs #absolute value
x.floor #floor
x.ceil #ceiling
x ** y #power
[edit] Run BASIC
print "exp:";chr$(9); EXP(1)
print "PI:";chr$(9); 22/7
print "Sqr2:";chr$(9); SQR(2)
print "Log2:";chr$(9); LOG(2) : REM Base 10
print "Exp2:";chr$(9); EXP(2)
print "Abs2:";chr$(9); ABS(-2)
print "Floor:";chr$(9); INT(1.534)
print "ceil:";chr$(9); val(using("###",1.534))
print "Power:";chr$(9); 1.23^4
exp: 2.71828183 PI: 3.14285707 Sqr2: 1.41421356 Log2: 0.693147181 Exp2: 7.3890561 Abs2: 2 Floor: 1 ceil: 2 Power: 2.28886641
[edit] Scheme
(sqrt x) ;square root
(log x) ;natural logarithm
(exp x) ;exponential
(abs x) ;absolute value
(floor x) ;floor
(ceiling x) ;ceiling
(expt x y) ;power
[edit] Seed7
The math.s7i library defines:
| E | # e (Euler's number) |
| PI | # Pi |
| sqrt(x) | # square root |
| log(x) | # natural logarithm - log base 10 is also available: log10(x)) |
| exp(x) | # exponential |
| abs(x) | # absolute value |
| floor(x) | # floor |
| ceil(x) | # ceiling |
The float.s7i library defines:
| x ** y | # power with integer exponent |
| x ** y | # power with float exponent |
[edit] Slate
numerics E.
numerics Pi.
n sqrt.
n log10. "base 10 logarithm"
n ln. "natural logarithm"
n log: m. "arbitrary base logarithm"
n exp. "exponential"
n abs. "absolute value"
n floor.
n ceiling.
n raisedTo: anotherNumber
[edit] Smalltalk
Float e.
Float pi.
aNumber sqrt.
aNumber log. "base 10 logarithm"
aNumber ln. "natural logarithm"
aNumber exp. "exponential"
aNumber abs. "absolute value"
aNumber floor.
aNumber ceiling.
aNumber raisedTo: anotherNumber
[edit] Standard ML
Math.e; (* e *)
Math.pi; (* pi *)
Math.sqrt x; (* square root *)
Math.ln x; (* natural logarithm--log base 10 also available (Math.log10) *)
Math.exp x; (* exponential *)
abs x; (* absolute value *)
floor x; (* floor *)
ceil x; (* ceiling *)
Math.pow (x, y); (* power *)
~ x; (* negation *)
[edit] Tcl
expr {exp(1)} ;# e
expr {4 * atan(1)} ;# pi -- also, simpler: expr acos(-1)
expr {sqrt($x)} ;# square root
expr {log($x)} ;# natural logarithm, also log10
expr {exp($x)} ;# exponential
expr {abs($x)} ;# absolute value
expr {floor($x)} ;# floor
expr {ceil($x)} ;# ceiling
expr {$x**$y} ;# power, also pow($x,$y)
The constants e and π are also available with high precision in a support library.
package require math::constants
math::constants::constants e pi
puts "e = $e, pi = $pi"
[edit] TI-89 BASIC
| Mathematical | TI-89 | Notes |
|---|---|---|
| e | ℯ |
(U+212F SCRIPT SMALL E) |
| π | π |
(U+03C0 GREEK SMALL LETTER PI) |
|
√(x) |
(U+221A SQUARE ROOT) |
| loge(x) | ln(x)
| |
| log10(x) | log(x)
| |
| logb(x) | log(b, x) |
The optional base argument comes first |
|
floor(x)
| |
|
ceiling(x)
| |
| xy | x^y
|
[edit] XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations
func real Power(X, Y); \X raised to the Y power
real X, Y;
return Exp(Y*Ln(X));
real E, Pi;
[Format(4, 16); \places shown before and after .
E:= Exp(1.0);
RlOut(0, E); CrLf(0);
RlOut(0, Ln(E)); CrLf(0);
CrLf(0);
Pi:= ATan2(0.0, -1.0); \Pi is also a defined constant
RlOut(0, Pi); CrLf(0);
RlOut(0, Cos(Pi)); CrLf(0);
CrLf(0);
RlOut(0, Sqrt(2.0)); CrLf(0); \Sqrt is a call to an intrinsic
RlOut(0, Log(100.0)); CrLf(0);
RlOut(0, Ln(Exp(123.456789))); CrLf(0);
CrLf(0);
RlOut(0, abs(-1234.5)); CrLf(0); \abs works for both reals & ints
CrLf(0);
RlOut(0, float(fix(1.999-0.5))); CrLf(0); \floor rounds toward -infinity
RlOut(0, float(fix(1.001+0.5))); CrLf(0); \ceiling rounds toward +infinity
RlOut(0, Power(sqrt(2.0), 4.0)); CrLf(0); \sqrt is an inline function and
] \ can be used for both reals & ints
Output:
2.7182818284590500 1.0000000000000000 3.1415926535897900 -1.0000000000000000 1.4142135623731000 2.0000000000000000 123.4567890000000000 1234.5000000000000000 1.0000000000000000 2.0000000000000000 4.0000000000000000
- Programming Tasks
- Basic language learning
- Arithmetic operations
- ACL2
- ActionScript
- Ada
- Aime
- ALGOL 68
- AutoHotkey
- AWK
- BASIC
- BBC BASIC
- Bc
- Bc -l
- C
- C++
- C sharp
- Chef
- Clojure
- Common Lisp
- D
- Delphi
- DWScript
- E
- Erlang
- Factor
- Fantom
- Forth
- Fortran
- Go
- Groovy
- Haskell
- HicEst
- Icon
- Unicon
- Icon Programming Library
- J
- Java
- JavaScript
- Liberty BASIC
- Logo
- Lua
- Maple
- Mathematica
- MAXScript
- Mercury
- Metafont
- МК-61/52
- Modula-3
- NetRexx
- Objeck
- OCaml
- Octave
- Oz
- PARI/GP
- Pascal
- Perl
- Perl 6
- PHP
- PL/I
- PicoLisp
- Pop11
- PowerShell
- PureBasic
- Python
- R
- Racket
- REXX
- RLaB
- Ruby
- Run BASIC
- Scheme
- Seed7
- Slate
- Smalltalk
- Standard ML
- Tcl
- Tcllib
- TI-89 BASIC
- XPL0
- GUISS/Omit
- M4/Omit
- ML/I/Omit
- UNIX Shell/Omit