Infinity: Difference between revisions

From Rosetta Code
Content added Content deleted
No edit summary
No edit summary
Line 5: Line 5:
=={{header|ActionScript}}==
=={{header|ActionScript}}==
ActionScript has the built in function isFinite() to test if a number is finite or not.
ActionScript has the built in function isFinite() to test if a number is finite or not.
<actionscript>
<lang actionscript>
trace(5 / 0); // outputs "Infinity"
trace(5 / 0); // outputs "Infinity"
trace(isFinite(5 / 0)); // outputs "false"
trace(isFinite(5 / 0)); // outputs "false"
</lang>
</actionscript>


=={{header|Ada}}==
=={{header|Ada}}==
<ada>
<lang ada>
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Text_IO; use Ada.Text_IO;


Line 36: Line 36:
Put_Line ("Infimum " & Float'Image (Inf));
Put_Line ("Infimum " & Float'Image (Inf));
end Infinities;
end Infinities;
</ada>
</lang>
The language-defined attribute Machine_Overflows is defined for each floating-point type. It is true when an overflow or divide-by-zero results in Constraint_Error exception propagation. When the underlying machine type is incapable to implement this semantics the attribute is false. It is to expect that on the machines with [[IEEE]] 754 hardware Machine_Overflows is true. The language-defined attributes Succ and Pred yield the value next or previous to the argument, correspondingly.
The language-defined attribute Machine_Overflows is defined for each floating-point type. It is true when an overflow or divide-by-zero results in Constraint_Error exception propagation. When the underlying machine type is incapable to implement this semantics the attribute is false. It is to expect that on the machines with [[IEEE]] 754 hardware Machine_Overflows is true. The language-defined attributes Succ and Pred yield the value next or previous to the argument, correspondingly.


Line 47: Line 47:


Here is the code that should work for any type on any machine:
Here is the code that should work for any type on any machine:
<ada>
<lang ada>
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Text_IO; use Ada.Text_IO;


Line 74: Line 74:
Put_Line ("Infimum " & Real'Image (Inf));
Put_Line ("Infimum " & Real'Image (Inf));
end Infinities;
end Infinities;
</ada>
</lang>
Sample output. Note that the compiler is required to generate Constraint_Error even if the hardware is [[IEEE]] 754. So the upper and lower bounds are 10.0 and -10.0:
Sample output. Note that the compiler is required to generate Constraint_Error even if the hardware is [[IEEE]] 754. So the upper and lower bounds are 10.0 and -10.0:
<pre>
<pre>
Line 117: Line 117:
=={{header|C}}==
=={{header|C}}==
{{works with|GCC}}
{{works with|GCC}}
<c>#include <stdlib.h>
<lang c>#include <stdlib.h>
#include <stdio.h>
#include <stdio.h>


Line 127: Line 127:
printf("%f\n", inf()); /* outputs "inf" */
printf("%f\n", inf()); /* outputs "inf" */
return 0;
return 0;
}</c>
}</lang>


C99 also has a macro for infinity:
C99 also has a macro for infinity:
<c>#define _ISOC99_SOURCE
<lang c>#define _ISOC99_SOURCE


#include <math.h>
#include <math.h>
Line 138: Line 138:
printf("%f\n", INFINITY);
printf("%f\n", INFINITY);
return 0;
return 0;
}</c>
}</lang>


=={{header|C++}}==
=={{header|C++}}==


<cpp>#include <limits>
<lang cpp>#include <limits>


double inf()
double inf()
Line 150: Line 150:
else
else
return std::numeric_limits<double>::max();
return std::numeric_limits<double>::max();
}</cpp>
}</lang>


=={{header|D}}==
=={{header|D}}==


<d>typeof(1.0) inf()
<lang d>typeof(1.0) inf()
{
{
return typeof(1.0).infinity;
return typeof(1.0).infinity;
}</d>
}</lang>


=={{header|E}}==
=={{header|E}}==
Line 241: Line 241:


=={{header|J}}==
=={{header|J}}==
Positive infinity is produced by the primary constant function<code> _: </code>
Positive infinity is produced by the primary constant function<tt> _: </tt>
<br>It is also represented directly as a numeric value by an underscore, used alone.
<br>It is also represented directly as a numeric value by an underscore, used alone.


Line 249: Line 249:
=={{header|Java}}==
=={{header|Java}}==
Java's floating-point types (<tt>float</tt>, <tt>double</tt>) all support infinity. You can get infinity from constants in the corresponding wrapper class; for example, <tt>Double</tt>:
Java's floating-point types (<tt>float</tt>, <tt>double</tt>) all support infinity. You can get infinity from constants in the corresponding wrapper class; for example, <tt>Double</tt>:
<java>double infinity = Double.POSITIVE_INFINITY; //defined as 1.0/0.0
<lang java>double infinity = Double.POSITIVE_INFINITY; //defined as 1.0/0.0
Double.isInfinite(infinity); //true</java>
Double.isInfinite(infinity); //true</lang>
As a function:
As a function:
<java>public static double getInf(){
<lang java>public static double getInf(){
return Double.POSITIVE_INFINITY;
return Double.POSITIVE_INFINITY;
}</java>
}</lang>
The largest possible number in Java (without using the <tt>Big</tt> classes) is also in the <tt>Double</tt> class.
The largest possible number in Java (without using the <tt>Big</tt> classes) is also in the <tt>Double</tt> class.
<java>double biggestNumber = Double.MAX_VALUE;</java>
<lang java>double biggestNumber = Double.MAX_VALUE;</lang>
Its value is (2-2<sup>-52</sup>)*2<sup>1023</sup> or 1.7976931348623157*10<sup>308</sup> (a.k.a. "big"). Other number classes (<tt>Integer</tt>, <tt>Long</tt>, <tt>Float</tt>, <tt>Byte</tt>, and <tt>Short</tt>) have maximum values that can be accessed in the same way.
Its value is (2-2<sup>-52</sup>)*2<sup>1023</sup> or 1.7976931348623157*10<sup>308</sup> (a.k.a. "big"). Other number classes (<tt>Integer</tt>, <tt>Long</tt>, <tt>Float</tt>, <tt>Byte</tt>, and <tt>Short</tt>) have maximum values that can be accessed in the same way.


=={{header|JavaScript}}==
=={{header|JavaScript}}==
JavaScript has a special global property called "Infinity":
JavaScript has a special global property called "Infinity":
<javascript>Infinity</javascript>
<lang javascript>Infinity</lang>
as well as constants in the Number class:
as well as constants in the Number class:
<javascript>Number.POSITIVE_INFINITY
<lang javascript>Number.POSITIVE_INFINITY
Number.NEGATIVE_INFINITY</javascript>
Number.NEGATIVE_INFINITY</lang>


The global isFinite() function tests for finiteness:
The global isFinite() function tests for finiteness:
<javascript>isFinite(x)</javascript>
<lang javascript>isFinite(x)</lang>


=={{header|Modula-3}}==
=={{header|Modula-3}}==
Line 290: Line 290:


=={{header|OCaml}}==
=={{header|OCaml}}==
<ocaml>infinity</ocaml>
<lang ocaml>infinity</lang>
is already a pre-defined value in OCaml.
is already a pre-defined value in OCaml.


Line 302: Line 302:
=={{header|Perl}}==
=={{header|Perl}}==
I'm don't know of the official way to get infinity. The following seems to work on my version of Perl:
I'm don't know of the official way to get infinity. The following seems to work on my version of Perl:
<perl>1e600</perl>
<lang perl>1e600</lang>


Unfortunately, "1.0 / 0.0" doesn't evaluate to infinity; but throws an exception.
Unfortunately, "1.0 / 0.0" doesn't evaluate to infinity; but throws an exception.
Line 308: Line 308:
=={{header|PHP}}==
=={{header|PHP}}==
This is how you get infinity:
This is how you get infinity:
<php>INF</php>
<lang php>INF</lang>
Unfortunately, "1.0 / 0.0" doesn't evaluate to infinity; but instead seems to evaluate to False, which is more like 0 than infinity.
Unfortunately, "1.0 / 0.0" doesn't evaluate to infinity; but instead seems to evaluate to False, which is more like 0 than infinity.


Line 328: Line 328:


=={{header|Ruby}}==
=={{header|Ruby}}==
<ruby>Infinity = 1.0/0</ruby>
<lang ruby>Infinity = 1.0/0</lang>

Revision as of 15:36, 3 February 2009

Task
Infinity
You are encouraged to solve this task according to the task description, using any language you may know.

Write a function which tests if infinity is supported for floating point numbers (this step should be omitted for languages where the language specification already demands the existence of infinity, e.g. by demanding IEEE numbers), and if so, returns positive infinity. Otherwise, return the largest possible number.

For languages with several floating point types, use the type of the literal constant 1.0 as floating point type.

ActionScript

ActionScript has the built in function isFinite() to test if a number is finite or not. <lang actionscript> trace(5 / 0); // outputs "Infinity" trace(isFinite(5 / 0)); // outputs "false" </lang>

Ada

<lang ada> with Ada.Text_IO; use Ada.Text_IO;

procedure Infinities is

  function Sup return Float is -- Only for predefined types
     Result : Float := Float'Last;
  begin
     if not Float'Machine_Overflows then
        Result := Float'Succ (Result);
     end if;
     return Result;
  end Sup;
  function Inf return Float is -- Only for predefined types
     Result : Float := Float'First;
  begin
     if not Float'Machine_Overflows then
        Result := Float'Pred (Result);
     end if;
     return Result;
  end Inf;

begin

  Put_Line ("Supremum" & Float'Image (Sup));
  Put_Line ("Infimum " & Float'Image (Inf));

end Infinities; </lang> The language-defined attribute Machine_Overflows is defined for each floating-point type. It is true when an overflow or divide-by-zero results in Constraint_Error exception propagation. When the underlying machine type is incapable to implement this semantics the attribute is false. It is to expect that on the machines with IEEE 754 hardware Machine_Overflows is true. The language-defined attributes Succ and Pred yield the value next or previous to the argument, correspondingly.

Sample output on a machine where Float is IEEE 754:

Supremum +Inf*******
Infimum -Inf*******

Note that the code above does not work for user-defined types, which may have range of values narrower than one of the underlying hardware type. This case represents one of the reasons why Ada programmers are advised not to use predefined floating-point types. There is a danger that the implementation of might be IEEE 754, and so the program semantics could be broken.

Here is the code that should work for any type on any machine: <lang ada> with Ada.Text_IO; use Ada.Text_IO;

procedure Infinities is

  type Real is digits 5 range -10.0..10.0;
  
  function Sup return Real is
     Result : Real := Real'Last;
  begin
     return Real'Succ (Result);
  exception
     when Constraint_Error =>
        return Result;
  end Sup;
  function Inf return Real is
     Result : Real := Real'First;
  begin
     return Real'Pred (Result);
  exception
     when Constraint_Error =>
        return Result;
  end Inf;

begin

  Put_Line ("Supremum" & Real'Image (Sup));
  Put_Line ("Infimum " & Real'Image (Inf));

end Infinities; </lang> Sample output. Note that the compiler is required to generate Constraint_Error even if the hardware is IEEE 754. So the upper and lower bounds are 10.0 and -10.0:

Supremum 1.0000E+01
Infimum -1.0000E+01

ALGOL 68

ALGOL 68R (from Royal Radar Establishment) has an infinity variable as part of the standard preclude, on the ICL 1900 Series mainframes the value of infinity is 5.79860446188₁₀76 (the same as max float).

Note: The underlying hardware may sometimes support an infinity, but the ALGOL 68 standard itself does not, and gives no way of setting a variable to either ±∞.

ALGOL 68 does have some 7 built in exceptions, these might be used to detect exceptions during transput, and so if the underlying hardware does support ∞, then it would be detected with a on value error while printing and if mended would appear as a field full of error char.

printf(($"max int: "gl$,max int));
printf(($"long max int: "gl$,long max int));
printf(($"long long max int: "gl$,long long max int));
printf(($"max real: "gl$,max real));
printf(($"long max real: "gl$,long max real));
printf(($"long long max real: "gl$,long long max real));
printf(($"error char: "gl$,error char))

ALGOL 68G-mk14.1 output:

max int: +2147483647 long max int: +99999999999999999999999999999999999 long long max int: +9999999999999999999999999999999999999999999999999999999999999999999999 max real: +1.79769313486235e+308 long max real: +1.000000000000000000000000e+999999 long long max real: +1.00000000000000000000000000000000000000000000000000000000000e+999999 error char: *

C

Works with: GCC

<lang c>#include <stdlib.h>

  1. include <stdio.h>

double inf() {

 return atof("infinity");

}

int main() {

 printf("%f\n", inf()); /* outputs "inf" */
 return 0;

}</lang>

C99 also has a macro for infinity: <lang c>#define _ISOC99_SOURCE

  1. include <math.h>
  2. include <stdio.h>

int main() {

 printf("%f\n", INFINITY);
 return 0;

}</lang>

C++

<lang cpp>#include <limits>

double inf() {

 if (std::numeric_limits<double>::has_infinity)
   return std::numeric_limits<double>::infinity();
 else
   return std::numeric_limits<double>::max();

}</lang>

D

<lang d>typeof(1.0) inf() {

 return typeof(1.0).infinity;

}</lang>

E

def infinityTask() {
    return Infinity # predefined variable holding positive infinity
}

Forth

: inf ( -- f ) 1e 0e f/ ;
inf f.    \ implementation specific. GNU Forth will output "inf"

: inf? ( f -- ? ) s" MAX-FLOAT" environment? drop f> ;
\ IEEE infinity is the only value for which this will return true

: has-inf ( -- ? ) ['] inf catch if false else inf? then ;

Fortran

ISO Fortran 2003 or later supports an IEEE_ARITHMETIC module which defines a wide range of intrinsic functions and types in support of IEEE floating point formats and arithmetic rules.

  program to_f_the_ineffable
     use, intrinsic :: ieee_arithmetic
     integer :: i
     real dimension(2) :: y, x = (/ 30, ieee_value(y,ieee_positive_inf) /)
     
     do i = 1, 2
        if (ieee_support_datatype(x(i))) then
           if (ieee_is_finite(x(i))) then
              print *, 'x(',i,') is finite'
           else
              print *, 'x(',i,') is infinite'
           end if
           
        else
           print *, 'x(',i,') is not in an IEEE-supported format'
        end if
     end do
  end program to_f_the_ineffable

ISO Fortran 90 or later supports a HUGE intrinsic which returns the largest value supported by the data type of the number given.

  real :: x
  real :: huge_real = huge(x)

Haskell

The Haskell 98 standard does not require full IEEE numbers, and the required operations on floating point numbers leave some degree of freedom to the implementation. Also, it's not possible to use the type of the literal 1.0 to decide which concrete type to use, because Haskell number literals are automatically converted.

Nevertheless, the following may come close to the task description:

maxRealFloat :: RealFloat a => a -> a
maxRealFloat x = encodeFloat b (e-1) `asTypeOf` x where
  b     = floatRadix x - 1
  (_,e) = floatRange x

infinity :: RealFloat a => a
infinity = if isInfinite inf then inf else maxRealFloat 1.0 where
  inf = 1/0 

Test for the two standard floating point types:

*Main> infinity :: Float
Infinity
*Main> infinity :: Double
Infinity

Or you can simply use division by 0:

Prelude> 1 / 0 :: Float
Infinity
Prelude> 1 / 0 :: Double
Infinity

Or use "read" to read the string representation:

Prelude> read "Infinity" :: Float
Infinity
Prelude> read "Infinity" :: Double
Infinity

IDL

IDL provides the standard IEEE values for _inf and _NaN in the !Values system structure:

print, !Values.f_infinity             ;; for normal floats or
print, !Values.D_infinity             ;; for doubles  

J

Positive infinity is produced by the primary constant function _:
It is also represented directly as a numeric value by an underscore, used alone.

Io

inf := 1/0

Java

Java's floating-point types (float, double) all support infinity. You can get infinity from constants in the corresponding wrapper class; for example, Double: <lang java>double infinity = Double.POSITIVE_INFINITY; //defined as 1.0/0.0 Double.isInfinite(infinity); //true</lang> As a function: <lang java>public static double getInf(){

  return Double.POSITIVE_INFINITY;

}</lang> The largest possible number in Java (without using the Big classes) is also in the Double class. <lang java>double biggestNumber = Double.MAX_VALUE;</lang> Its value is (2-2-52)*21023 or 1.7976931348623157*10308 (a.k.a. "big"). Other number classes (Integer, Long, Float, Byte, and Short) have maximum values that can be accessed in the same way.

JavaScript

JavaScript has a special global property called "Infinity": <lang javascript>Infinity</lang> as well as constants in the Number class: <lang javascript>Number.POSITIVE_INFINITY Number.NEGATIVE_INFINITY</lang>

The global isFinite() function tests for finiteness: <lang javascript>isFinite(x)</lang>

Modula-3

IEEESpecial contains 3 variables defining negative infinity, positive infinity, and NaN for all 3 floating point types in Modula-3 (REAL, LONGREAL, and EXTENDED).

If the implementation doesn't support IEEE floats, the program prints arbitrary values (Critical Mass Modula-3 implementation does support IEEE floats).

MODULE Inf EXPORTS Main;

IMPORT IO, IEEESpecial;

BEGIN
  IO.PutReal(IEEESpecial.RealPosInf);
  IO.Put("\n");
END Inf.

Output:

Infinity

OCaml

<lang ocaml>infinity</lang> is already a pre-defined value in OCaml.

# infinity;;
- : float = infinity
# 1.0 /. 0.0;;
- : float = infinity

Perl

I'm don't know of the official way to get infinity. The following seems to work on my version of Perl: <lang perl>1e600</lang>

Unfortunately, "1.0 / 0.0" doesn't evaluate to infinity; but throws an exception.

PHP

This is how you get infinity: <lang php>INF</lang> Unfortunately, "1.0 / 0.0" doesn't evaluate to infinity; but instead seems to evaluate to False, which is more like 0 than infinity.

PHP has functions is_finite() and is_infinite() to test for infiniteness.

Python

This is how you get infinity:

>>> float('infinity')
inf

Note: When passing in a string to float(), values for NaN and Infinity may be returned, depending on the underlying C library. The specific set of strings accepted which cause these values to be returned depends entirely on the underlying C library used to compile Python itself, and is known to vary.
The Decimal module explicitly supports +/-infinity Nan, +/-0.0, etc without exception.


Floating-point division by 0 doesn't give you infinity, it raises an exception:

>>> 1.0 / 0.0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: float division

Ruby

<lang ruby>Infinity = 1.0/0</lang>