Infinity: Difference between revisions

From Rosetta Code
Content added Content deleted
(→‎{{header|Io}}: added alternative Io test)
Line 295: Line 295:
=={{header|Io}}==
=={{header|Io}}==
<lang io>inf := 1/0</lang>
<lang io>inf := 1/0</lang>

or

<lang io>Number constants inf</lang>


=={{header|Java}}==
=={{header|Java}}==

Revision as of 03:13, 5 March 2010

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 positive floating point 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

Getting rid of IEEE ideals

There is a simple way to strip IEEE 754 ideals (non-numeric values) from a predefined floating-point type such as Float or Long_Float: <lang ada>subtype Safe_Float is Float range Float'Range;</lang> The subtype Safe_Float keeps all the range of Float, yet behaves properly upon overflow, underflow and zero-divide.

ALGOL 68

ALGOL 68R (from Royal Radar Establishment) has an infinity variable as part of the standard prelude, 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.

<lang algol68>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))</lang>ALGOL 68G-mk14.1 output:<lang algol68>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: *</lang>

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>

C#

<lang csharp>class Program {

   static void Main(string[] args) {
       double infinity = Double.PositiveInfinity;
   }

}</lang>

Common Lisp

Common Lisp does not specify an infinity value. Some implementations may have support for IEEE infinity, however. For instance, CMUCL supports IEEE Special Values. Common Lisp does specify that implementations define constants with most (and least) positive (and negative) values. These may vary between implementations.

Works with: LispWorks

5.1.2, Intel, OS X, 32-bit

<lang lisp>> (apropos "MOST-POSITIVE" :cl) MOST-POSITIVE-LONG-FLOAT, value: 1.7976931348623158D308 MOST-POSITIVE-SHORT-FLOAT, value: 3.4028172S38 MOST-POSITIVE-SINGLE-FLOAT, value: 3.4028235E38 MOST-POSITIVE-DOUBLE-FLOAT, value: 1.7976931348623158D308 MOST-POSITIVE-FIXNUM, value: 536870911

> (apropos "MOST-NEGATIVE" :cl) MOST-NEGATIVE-SINGLE-FLOAT, value: -3.4028235E38 MOST-NEGATIVE-LONG-FLOAT, value: -1.7976931348623158D308 MOST-NEGATIVE-SHORT-FLOAT, value: -3.4028172S38 MOST-NEGATIVE-DOUBLE-FLOAT, value: -1.7976931348623158D308 MOST-NEGATIVE-FIXNUM, value: -536870912</lang>

D

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

 return typeof(1.0).infinity;

}</lang>

E

<lang e>def infinityTask() {

   return Infinity # predefined variable holding positive infinity

}</lang>

Factor

<lang factor>1/0.</lang>

Forth

<lang 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 ;</lang>

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. <lang fortran>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</lang>

ISO Fortran 90 or later supports a HUGE intrinsic which returns the largest value supported by the data type of the number given. <lang fortran>real :: x real :: huge_real = huge(x)</lang>

Groovy

Groovy, like Java, requires full support for IEEE 32-bit (Float) and 64-bit (Double) formats. So the solution function would simply return either the Float or Double constant encoded as IEEE infinity. <lang groovy>def biggest = { Double.POSITIVE_INFINITY }</lang>

Test program: <lang groovy>println biggest() printf ( "0x%xL \n", Double.doubleToLongBits(biggest()) )</lang>

Output:

Infinity
0x7ff0000000000000L

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:

<lang haskell>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</lang>

Test for the two standard floating point types:

<lang haskell>*Main> infinity :: Float Infinity

  • Main> infinity :: Double

Infinity</lang>

Or you can simply use division by 0: <lang haskell>Prelude> 1 / 0 :: Float Infinity Prelude> 1 / 0 :: Double Infinity</lang>

Or use "read" to read the string representation: <lang haskell>Prelude> read "Infinity" :: Float Infinity Prelude> read "Infinity" :: Double Infinity</lang>

IDL

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

<lang idl>print, !Values.f_infinity  ;; for normal floats or print, !Values.D_infinity  ;; for doubles</lang>

J

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

Example: <lang j>

  _ * 5 NB. multiplying infinity to 5 results in infinity

_

  5 % _ NB. dividing 5 by infinity results in 0

0

  5 % 0 NB. dividing 5 by 0 results in infinity

_ </lang>

Io

<lang io>inf := 1/0</lang>

or

<lang io>Number constants inf</lang>

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>

Lua

<lang lua> function infinity()

 return 1/0 --lua uses unboxed C floats for all numbers

end </lang>

Mathematica

Mathematica has infinity built-in as a symbol. Which can be used throughout the software: <lang Mathematica>Sum[1/n^2,{n,Infinity}] 1/Infinity Integrate[Exp[-x^2], {x, -Infinity, Infinity}] 10^100 < Infinity</lang> gives back: <lang Mathematica>Pi^2/6 0 Sqrt[Pi] True</lang> Moreover Mathematica has 2 other variables that represent 'infinity': DirectedInfinity[r] and ComplexInfinity. DirectInfinity[r] represents an infinite quantity with complex direction r. ComplexInfinity represents an infinite quantity with an undetermined direction; like 1/0. Which has infinite size but undetermined direction. So the general infinity is DirectedInfinity, however if the direction is unknown it will turn to ComplexInfinity, DirectedInfinity[-1] will return -infinity and DirectedInfinity[1] will return infinity. Directed infinity can, for example, be used to integrate over an infinite domain with a given complex direction: one might want to integrate Exp[-x^2]/(x^2-1) from 0 to DirectedInfinity[Exp[I Pi/4]]: <lang Mathematica>Integrate[Exp[-x^2]/(x^2 - 1), {x, 0, DirectedInfinity[Exp[I Pi/4]]}]</lang> gives back: <lang Mathematica>-((Pi (I+Erfi[1]))/(2 E))</lang>

MATLAB

<lang Matlab>function [hasInfinity] = checkforinfinity()

  if ( isinf(inf) == 1 )
     hasInfinity = 1;
  end</lang>

Metafont

Metafont numbers are a little bit odd (it uses fixed binary arithmetic). For Metafont, the biggest number (and so the one which is also considered to be infinity) is 4095.99998. In fact, in the basic set of macros for Metafont, we can read

<lang metafont>infinity := 4095.99998;</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). <lang modula3>MODULE Inf EXPORTS Main;

IMPORT IO, IEEESpecial;

BEGIN

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

END Inf.</lang>

Output:

Infinity

OCaml

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

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

Oz

<lang oz>declare

 PosInf = 1./0.
 NegInf = ~1./0.

in

 {Show PosInf}
 {Show NegInf}
 %% some assertion
 42. / PosInf = 0.
 42. / NegInf = 0.
 PosInf * PosInf = PosInf
 PosInf * NegInf = NegInf
 NegInf * NegInf = PosInf</lang>

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.

PL/I

<lang PL/I> declare x float, y float (15), z float (18);

put skip list (huge(x), huge(y), huge(z)); </lang>

PowerShell

Since PowerShell is built on .NET, floating-point numbers are always capable of representing infinity. <lang powershell>function infinity {

   [double]::PositiveInfinity

}</lang>

Python

This is how you get infinity: <lang python>>>> float('infinity') inf</lang> 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: <lang python>>>> 1.0 / 0.0 Traceback (most recent call last):

 File "<stdin>", line 1, in <module>

ZeroDivisionError: float division</lang>

R

<lang R> Inf #positive infinity

-Inf                   #negative infinity 
.Machine$double.xmax   # largest finite floating-point number
is.finite              # function to test to see if a number is finite
  1. function that returns the input if it is finite, otherwise returns (plus or minus) the largest finite floating-point number
forcefinite <- function(x) ifelse(is.finite(x), x, sign(x)*.Machine$double.xmax)
forcefinite(c(1, -1, 0, .Machine$double.xmax, -.Machine$double.xmax, Inf, -Inf))
  1. [1] 1.000000e+00 -1.000000e+00 0.000000e+00 1.797693e+308
  2. [5] -1.797693e+308 1.797693e+308 -1.797693e+308</lang>

Ruby

Infinity is a Float value <lang ruby>a = 1.0/0 # => Infinity a.finite? # => false a.infinite? # => 1

a = -1/0.0 # => -Infinity a.infinite? # => -1

a = Float::MAX # => 1.79769313486232e+308 a.finite? # => true a.infinite? # => nil</lang>

Scala

Scala mandates IEEE numbers. The type for 1.0 is Double, whose positive infinity is given by the following constant:

<lang scala>Math.POS_INF_DOUBLE</lang>

There's also a NEG constant for negative infinity, and FLOAT constants for the other floating point type, Float.

The maximum, non-infinity, number for Double is given by the following constant:

<lang scala>Math.MAX_DOUBLE</lang>

Seed7

Seed7's floating-point type (float) supports infinity. The include library "float.s7i" defines the constant "Infinity" as: <lang seed7>const float: Infinity is 1.0 / 0.0;</lang> Checks for infinity can be done by comparing with this constant.

Slate

<lang slate>PositiveInfinity</lang>

Standard ML

<lang sml>Real.posInf</lang>

- Real.posInf;
val it = inf : real
- 1.0 / 0.0;
val it = inf : real

Tcl

Works with: Tcl version 8.5

Tcl 8.5 has Infinite as a floating point value, not an integer value <lang tcl>package require Tcl 8.5

expr {1.0 / 0}  ;# ==> Inf expr {-1.0 / 0} ;# ==> -Inf expr {inf}  ;# ==> Inf expr {1 / 0}  ;# ==> "divide by zero" error; Inf not part of range of integer division</lang>

A maximal integer is not easy to find, as Tcl switches to unbounded integers when a 64-bit integer is about to roll over: <lang Tcl>% format %lx -1  ;# all bits set ffffffffffffffff

% regsub f 0x[format %lx -1] 7 ;# unset the sign bit for positive 0x7fffffffffffffff

% set ii [expr [regsub f 0x[format %lx -1] 7]] ;# show as decimal 9223372036854775807

% incr ii 9223372036854775808 ;# silently upgrade to unbounded integer, still positive</lang> A theoretical MAXINT, though very impractical, could be

string repeat 9 [expr 2**32-1]

TI-89 BASIC

<lang ti89b>∞</lang>

Ursala

IEEE double precision floating point numbers are a primitive type in Ursala. This function returns IEEE double precision infinity when applied to any argument, using the value inf, which is declared as a constant in the flo library.


<lang Ursala>#import flo

infinity = inf!</lang>

Visual Basic

Visual Basic 6

Positive infinity, negative infinity and indefinite number (usable as NaN?) can be generated by deliberately dividing by zero under the influence of an on error resume next

Implementation

<lang vb>

   Dim PlusInfinity as Double
   Dim MinusInfinity as Double
   Dim IndefiniteNumber as Double
   On Error Resume Next
   PlusInfinity = 1 / 0
   MinusInfinity = -1 / 0
   IndefiniteNumber = 0 / 0

</lang>

Stored internally as

1.#INF
-1.#INF
-1.#IND