Infinity: Difference between revisions
Not a robot (talk | contribs) Add APL |
|||
(31 intermediate revisions by 18 users not shown) | |||
Line 13: | Line 13: | ||
=={{header|11l}}== |
=={{header|11l}}== |
||
<lang |
<syntaxhighlight lang="11l">print(Float.infinity)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 22: | Line 22: | ||
=={{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. |
||
< |
<syntaxhighlight lang="actionscript">trace(5 / 0); // outputs "Infinity" |
||
trace(isFinite(5 / 0)); // outputs "false"</ |
trace(isFinite(5 / 0)); // outputs "false"</syntaxhighlight> |
||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
< |
<syntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO; |
||
procedure Infinities is |
procedure Infinities is |
||
Line 49: | Line 49: | ||
Put_Line ("Supremum" & Float'Image (Sup)); |
Put_Line ("Supremum" & Float'Image (Sup)); |
||
Put_Line ("Infimum " & Float'Image (Inf)); |
Put_Line ("Infimum " & Float'Image (Inf)); |
||
end Infinities;</ |
end Infinities;</syntaxhighlight> |
||
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 60: | Line 60: | ||
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: |
||
< |
<syntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO; |
||
procedure Infinities is |
procedure Infinities is |
||
Line 85: | Line 85: | ||
Put_Line ("Supremum" & Real'Image (Sup)); |
Put_Line ("Supremum" & Real'Image (Sup)); |
||
Put_Line ("Infimum " & Real'Image (Inf)); |
Put_Line ("Infimum " & Real'Image (Inf)); |
||
end Infinities;</ |
end Infinities;</syntaxhighlight> |
||
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 93: | Line 93: | ||
===Getting rid of IEEE ideals=== |
===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: |
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: |
||
< |
<syntaxhighlight lang="ada">subtype Safe_Float is Float range Float'Range;</syntaxhighlight> |
||
The subtype Safe_Float keeps all the range of Float, yet behaves properly upon overflow, underflow and zero-divide. |
The subtype Safe_Float keeps all the range of Float, yet behaves properly upon overflow, underflow and zero-divide. |
||
Line 107: | Line 107: | ||
ALGOL 68 does have some 7 built in [[Exceptions#ALGOL_68|exceptions]], these might be used to detect exceptions during transput, and so <u>if</u> the underlying hardware <u>does</u> 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''. |
ALGOL 68 does have some 7 built in [[Exceptions#ALGOL_68|exceptions]], these might be used to detect exceptions during transput, and so <u>if</u> the underlying hardware <u>does</u> 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''. |
||
< |
<syntaxhighlight lang="algol68">printf(($"max int: "gl$,max int)); |
||
printf(($"long max int: "gl$,long max int)); |
printf(($"long max int: "gl$,long max int)); |
||
printf(($"long long max int: "gl$,long long max int)); |
printf(($"long long max int: "gl$,long long max int)); |
||
Line 113: | Line 113: | ||
printf(($"long max real: "gl$,long max real)); |
printf(($"long max real: "gl$,long max real)); |
||
printf(($"long long max real: "gl$,long long max real)); |
printf(($"long long max real: "gl$,long long max real)); |
||
printf(($"error char: "gl$,error char))</ |
printf(($"error char: "gl$,error char))</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 132: | Line 132: | ||
that support infinity, this will be infinity. Otherwise, it will be some large, but finite value. |
that support infinity, this will be infinity. Otherwise, it will be some large, but finite value. |
||
<lang |
<syntaxhighlight lang="apl">inf ← {⌊/⍬}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 143: | Line 143: | ||
=={{header|Argile}}== |
=={{header|Argile}}== |
||
{{trans|C}} (simplified) |
{{trans|C}} (simplified) |
||
< |
<syntaxhighlight lang="argile">use std |
||
printf "%f\n" atof "infinity" (: this prints "inf" :) |
printf "%f\n" atof "infinity" (: this prints "inf" :) |
||
#extern :atof<text>: -> real</ |
#extern :atof<text>: -> real</syntaxhighlight> |
||
=={{header| |
=={{header|Arturo}}== |
||
<syntaxhighlight lang="rebol">print infinity |
|||
<lang AWK> BEGIN { |
|||
print neg infinity</syntaxhighlight> |
|||
{{out}} |
|||
<pre>∞ |
|||
-∞</pre> |
|||
=={{header|AWK}}== |
|||
<syntaxhighlight lang="awk"> BEGIN { |
|||
k=1; |
k=1; |
||
while (2^(k-1) < 2^k) k++; |
while (2^(k-1) < 2^k) k++; |
||
INF = 2^k; |
INF = 2^k; |
||
print INF; |
print INF; |
||
}</ |
}</syntaxhighlight> |
||
This has been tested with GAWK 3.1.7 and MAWK, both return |
This has been tested with GAWK 3.1.7 and MAWK, both return |
||
<pre> inf </pre> |
<pre> inf </pre> |
||
=={{header| |
=={{header|BASIC}}== |
||
==={{header|BASIC256}}=== |
|||
<syntaxhighlight lang="basic256">onerror TratoError |
|||
infinity = 1e300*1e300 |
|||
end |
|||
TratoError: |
|||
if lasterror = 29 then print lasterrormessage |
|||
return</syntaxhighlight> |
|||
==={{header|BBC BASIC}}=== |
|||
{{works with|BBC BASIC for Windows}} |
{{works with|BBC BASIC for Windows}} |
||
< |
<syntaxhighlight lang="bbcbasic"> *FLOAT 64 |
||
PRINT FNinfinity |
PRINT FNinfinity |
||
END |
END |
||
Line 179: | Line 198: | ||
RESTORE ERROR |
RESTORE ERROR |
||
UNTIL maxpos = prev |
UNTIL maxpos = prev |
||
= maxpos</ |
= maxpos</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 185: | Line 204: | ||
</pre> |
</pre> |
||
=={{header|bootBASIC}}== |
==={{header|bootBASIC}}=== |
||
There are no floating point numbers in bootBASIC. All numbers and variables are 2 byte unsigned integers. |
|||
The code below can't print anything on the screen, plus the program won't end. No way is currently known to break out of the program. |
The code below can't print anything on the screen, plus the program won't end. No way is currently known to break out of the program. |
||
<lang |
<syntaxhighlight lang="BASIC">10 print 1/0</syntaxhighlight> |
||
=={{header|BQN}}== |
=={{header|BQN}}== |
||
Line 209: | Line 230: | ||
C89 has a macro HUGE_VAL in <math.h>. HUGE_VAL is a <tt>double</tt>. HUGE_VAL will be infinity if infinity exists, else it will be the largest possible number. HUGE_VAL is a <tt>double</tt>. |
C89 has a macro HUGE_VAL in <math.h>. HUGE_VAL is a <tt>double</tt>. HUGE_VAL will be infinity if infinity exists, else it will be the largest possible number. HUGE_VAL is a <tt>double</tt>. |
||
< |
<syntaxhighlight lang="c">#include <math.h> /* HUGE_VAL */ |
||
#include <stdio.h> /* printf() */ |
#include <stdio.h> /* printf() */ |
||
Line 219: | Line 240: | ||
printf("%g\n", inf()); |
printf("%g\n", inf()); |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
The output from the above program might be "inf", "1.#INF", or something else. |
The output from the above program might be "inf", "1.#INF", or something else. |
||
Line 225: | Line 246: | ||
C99 also has a macro for infinity: |
C99 also has a macro for infinity: |
||
< |
<syntaxhighlight lang="c">#define _ISOC99_SOURCE |
||
#include <math.h> |
#include <math.h> |
||
Line 233: | Line 254: | ||
printf("%g\n", INFINITY); |
printf("%g\n", INFINITY); |
||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|C sharp|C#}}== |
=={{header|C sharp|C#}}== |
||
< |
<syntaxhighlight lang="csharp">using System; |
||
class Program |
class Program |
||
Line 249: | Line 270: | ||
Console.WriteLine(PositiveInfinity()); |
Console.WriteLine(PositiveInfinity()); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Output: |
Output: |
||
<lang>Infinity</ |
<syntaxhighlight lang="text">Infinity</syntaxhighlight> |
||
=={{header|C++}}== |
=={{header|C++}}== |
||
< |
<syntaxhighlight lang="cpp">#include <limits> |
||
double inf() |
double inf() |
||
Line 263: | Line 284: | ||
else |
else |
||
return std::numeric_limits<double>::max(); |
return std::numeric_limits<double>::max(); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
{{trans|Java}} |
{{trans|Java}} |
||
Java's floating-point types (float, double) all support infinity. Clojure has literals for infinity: |
Java's floating-point types (float, double) all support infinity. Clojure has literals for infinity: |
||
< |
<syntaxhighlight lang="clojure">##Inf ;; same as Double/POSITIVE_INFINITY |
||
##-Inf ;; same as Double/NEGATIVE_INFINITY |
##-Inf ;; same as Double/NEGATIVE_INFINITY |
||
(Double/isInfinite ##Inf) ;; true</ |
(Double/isInfinite ##Inf) ;; true</syntaxhighlight> |
||
The largest possible number in Java (without using the Big classes) is also in the Double class |
The largest possible number in Java (without using the Big classes) is also in the Double class |
||
Line 280: | Line 301: | ||
JavaScript has a special global property called "Infinity": |
JavaScript has a special global property called "Infinity": |
||
<lang |
<syntaxhighlight lang="coffeescript">Infinity</syntaxhighlight> |
||
as well as constants in the Number class: |
as well as constants in the Number class: |
||
< |
<syntaxhighlight lang="coffeescript">Number.POSITIVE_INFINITY |
||
Number.NEGATIVE_INFINITY</ |
Number.NEGATIVE_INFINITY</syntaxhighlight> |
||
The global isFinite function tests for finiteness: |
The global isFinite function tests for finiteness: |
||
<lang |
<syntaxhighlight lang="coffeescript">isFinite x</syntaxhighlight> |
||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
Line 294: | Line 315: | ||
{{works with|LispWorks}} 5.1.2, Intel, OS X, 32-bit |
{{works with|LispWorks}} 5.1.2, Intel, OS X, 32-bit |
||
< |
<syntaxhighlight lang="lisp">> (apropos "MOST-POSITIVE" :cl) |
||
MOST-POSITIVE-LONG-FLOAT, value: 1.7976931348623158D308 |
MOST-POSITIVE-LONG-FLOAT, value: 1.7976931348623158D308 |
||
MOST-POSITIVE-SHORT-FLOAT, value: 3.4028172S38 |
MOST-POSITIVE-SHORT-FLOAT, value: 3.4028172S38 |
||
Line 306: | Line 327: | ||
MOST-NEGATIVE-SHORT-FLOAT, value: -3.4028172S38 |
MOST-NEGATIVE-SHORT-FLOAT, value: -3.4028172S38 |
||
MOST-NEGATIVE-DOUBLE-FLOAT, value: -1.7976931348623158D308 |
MOST-NEGATIVE-DOUBLE-FLOAT, value: -1.7976931348623158D308 |
||
MOST-NEGATIVE-FIXNUM, value: -536870912</ |
MOST-NEGATIVE-FIXNUM, value: -536870912</syntaxhighlight> |
||
=={{header|Component Pascal}}== |
=={{header|Component Pascal}}== |
||
BlackBox Component Builder |
BlackBox Component Builder |
||
< |
<syntaxhighlight lang="oberon2"> |
||
MODULE Infinity; |
MODULE Infinity; |
||
IMPORT StdLog; |
IMPORT StdLog; |
||
Line 322: | Line 343: | ||
END Do; |
END Do; |
||
</syntaxhighlight> |
|||
</lang> |
|||
Execute: ^Q Infinity.Do<br/> |
Execute: ^Q Infinity.Do<br/> |
||
Output: |
Output: |
||
Line 331: | Line 352: | ||
=={{header|D}}== |
=={{header|D}}== |
||
< |
<syntaxhighlight lang="d">auto inf() { |
||
return typeof(1.5).infinity; |
return typeof(1.5).infinity; |
||
} |
} |
||
void main() {}</ |
void main() {}</syntaxhighlight> |
||
=={{header|Delphi}}== |
=={{header|Delphi}}== |
||
Delphi defines the following constants in Math: |
Delphi defines the following constants in Math: |
||
< |
<syntaxhighlight lang="delphi"> Infinity = 1.0 / 0.0; |
||
NegInfinity = -1.0 / 0.0;</ |
NegInfinity = -1.0 / 0.0;</syntaxhighlight> |
||
Test for infinite value using: |
Test for infinite value using: |
||
<lang |
<syntaxhighlight lang="delphi">Math.IsInfinite()</syntaxhighlight> |
||
=={{header|Dyalect}}== |
=={{header|Dyalect}}== |
||
Line 350: | Line 371: | ||
Dyalect floating point number support positive infinity: |
Dyalect floating point number support positive infinity: |
||
< |
<syntaxhighlight lang="dyalect">func infinityTask() => Float.Infinity</syntaxhighlight> |
||
Float.inf() |
|||
}</lang> |
|||
=={{header|E}}== |
=={{header|E}}== |
||
< |
<syntaxhighlight lang="e">def infinityTask() { |
||
return Infinity # predefined variable holding positive infinity |
return Infinity # predefined variable holding positive infinity |
||
}</ |
}</syntaxhighlight> |
||
=={{header|EasyLang}}== |
|||
<syntaxhighlight lang=text> |
|||
print number "inf" |
|||
# or |
|||
print 1 / 0 |
|||
</syntaxhighlight> |
|||
=={{header|Eiffel}}== |
=={{header|Eiffel}}== |
||
< |
<syntaxhighlight lang="eiffel"> |
||
class |
class |
||
APPLICATION |
APPLICATION |
||
Line 380: | Line 407: | ||
end |
end |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
Line 396: | Line 423: | ||
floating and MAXLONGREAL for double precision floating. An infinity test can be achieved with |
floating and MAXLONGREAL for double precision floating. An infinity test can be achieved with |
||
an EXCEPTION: |
an EXCEPTION: |
||
<syntaxhighlight lang="erre"> |
|||
<lang ERRE> |
|||
PROGRAM INFINITY |
PROGRAM INFINITY |
||
Line 412: | Line 439: | ||
END WHILE |
END WHILE |
||
END PROGRAM |
END PROGRAM |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Euphoria}}== |
=={{header|Euphoria}}== |
||
< |
<syntaxhighlight lang="euphoria">constant infinity = 1E400 |
||
? infinity -- outputs "inf"</ |
? infinity -- outputs "inf"</syntaxhighlight> |
||
=={{header|F_Sharp|F#}}== |
=={{header|F_Sharp|F#}}== |
||
< |
<syntaxhighlight lang="fsharp"> |
||
printfn "%f" (1.0/0.0) |
printfn "%f" (1.0/0.0) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 430: | Line 457: | ||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
<lang |
<syntaxhighlight lang="factor">1/0.</syntaxhighlight> |
||
=={{header|Fantom}}== |
=={{header|Fantom}}== |
||
Line 436: | Line 463: | ||
Fantom's <code>Float</code> data type is an IEEE 754 64-bit floating point type. Positive infinity is represented by the constant <code>posInf</code>. |
Fantom's <code>Float</code> data type is an IEEE 754 64-bit floating point type. Positive infinity is represented by the constant <code>posInf</code>. |
||
< |
<syntaxhighlight lang="fantom"> |
||
class Main |
class Main |
||
{ |
{ |
||
Line 442: | Line 469: | ||
public static Void main () { echo (getInfinity ()) } |
public static Void main () { echo (getInfinity ()) } |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Forth}}== |
=={{header|Forth}}== |
||
< |
<syntaxhighlight lang="forth">: inf ( -- f ) 1e 0e f/ ; |
||
inf f. \ implementation specific. GNU Forth will output "inf" |
inf f. \ implementation specific. GNU Forth will output "inf" |
||
Line 451: | Line 478: | ||
\ IEEE infinity is the only value for which this will return true |
\ IEEE infinity is the only value for which this will return true |
||
: has-inf ( -- ? ) ['] inf catch if false else inf? then ;</ |
: has-inf ( -- ? ) ['] inf catch if false else inf? then ;</syntaxhighlight> |
||
=={{header|Fortran}}== |
=={{header|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. |
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. |
||
< |
<syntaxhighlight lang="fortran">program to_f_the_ineffable |
||
use, intrinsic :: ieee_arithmetic |
use, intrinsic :: ieee_arithmetic |
||
integer :: i |
integer :: i |
||
Line 472: | Line 499: | ||
end if |
end if |
||
end do |
end do |
||
end program to_f_the_ineffable</ |
end program to_f_the_ineffable</syntaxhighlight> |
||
ISO Fortran 90 or later supports a HUGE intrinsic which returns the largest value supported by the data type of the number given. |
ISO Fortran 90 or later supports a HUGE intrinsic which returns the largest value supported by the data type of the number given. |
||
< |
<syntaxhighlight lang="fortran">real :: x |
||
real :: huge_real = huge(x)</ |
real :: huge_real = huge(x)</syntaxhighlight> |
||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
< |
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64 |
||
#Include "crt/math.bi" |
#Include "crt/math.bi" |
||
Line 487: | Line 514: | ||
Print d; " (String representation of Positive Infinity)" |
Print d; " (String representation of Positive Infinity)" |
||
Sleep |
Sleep |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
1.#INF (String representation of Positive Infinity) |
1.#INF (String representation of Positive Infinity) |
||
</pre> |
|||
=={{header|FutureBasic}}== |
|||
FB has a native definition for infinite floating point types. As demonstrated below, it returns "inf". |
|||
<syntaxhighlight lang="futurebasic"> |
|||
printf @"%g", INFINITY |
|||
HandleEvents |
|||
</syntaxhighlight> |
|||
{{output}} |
|||
<pre> |
|||
inf |
|||
</pre> |
</pre> |
||
=={{header|Fōrmulæ}}== |
=={{header|Fōrmulæ}}== |
||
{{FormulaeEntry|page=https://formulae.org/?script=examples/Infinity}} |
|||
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation —i.e. XML, JSON— they are intended for storage and transfer purposes more than visualization and edition. |
|||
'''Solution''' |
|||
Fōrmulæ does not use floating point numbers, but arbitrary-size integers and arbitrary-precision decimal numbers. |
|||
Infinity is a predefined expression in Fōrmulæ. |
|||
Reduction of certain expressions can produce it: |
|||
[[File:Fōrmulæ - Infinity 01.png]] |
|||
Programs in Fōrmulæ are created/edited online in its [https://formulae.org website], However they run on execution servers. By default remote servers are used, but they are limited in memory and processing power, since they are intended for demonstration and casual use. A local server can be downloaded and installed, it has no limitations (it runs in your own computer). Because of that, example programs can be fully visualized and edited, but some of them will not run if they require a moderate or heavy computation/memory resources, and no local server is being used. |
|||
[[File:Fōrmulæ - Infinity 02.png]] |
|||
In '''[https://formulae.org/?example=Infinity this]''' page you can see the program(s) related to this task and their results. |
|||
=={{header|GAP}}== |
=={{header|GAP}}== |
||
< |
<syntaxhighlight lang="gap"># Floating point infinity |
||
inf := FLOAT_INT(1) / FLOAT_INT(0); |
inf := FLOAT_INT(1) / FLOAT_INT(0); |
||
Line 511: | Line 559: | ||
# GAP has also a formal ''infinity'' value |
# GAP has also a formal ''infinity'' value |
||
infinity in Cyclotomics; |
infinity in Cyclotomics; |
||
# true</ |
# true</syntaxhighlight> |
||
=={{header|Go}}== |
=={{header|Go}}== |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 532: | Line 580: | ||
x = posInf() // test function |
x = posInf() // test function |
||
fmt.Println(x, math.IsInf(x, 1)) // demonstrate result |
fmt.Println(x, math.IsInf(x, 1)) // demonstrate result |
||
}</ |
}</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 540: | Line 588: | ||
=={{header|Groovy}}== |
=={{header|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. |
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. |
||
< |
<syntaxhighlight lang="groovy">def biggest = { Double.POSITIVE_INFINITY }</syntaxhighlight> |
||
Test program: |
Test program: |
||
< |
<syntaxhighlight lang="groovy">println biggest() |
||
printf ( "0x%xL \n", Double.doubleToLongBits(biggest()) )</ |
printf ( "0x%xL \n", Double.doubleToLongBits(biggest()) )</syntaxhighlight> |
||
Output: |
Output: |
||
Line 556: | Line 604: | ||
Nevertheless, the following may come close to the task description: |
Nevertheless, the following may come close to the task description: |
||
< |
<syntaxhighlight lang="haskell">maxRealFloat :: RealFloat a => a -> a |
||
maxRealFloat x = encodeFloat b (e-1) `asTypeOf` x where |
maxRealFloat x = encodeFloat b (e-1) `asTypeOf` x where |
||
b = floatRadix x - 1 |
b = floatRadix x - 1 |
||
Line 563: | Line 611: | ||
infinity :: RealFloat a => a |
infinity :: RealFloat a => a |
||
infinity = if isInfinite inf then inf else maxRealFloat 1.0 where |
infinity = if isInfinite inf then inf else maxRealFloat 1.0 where |
||
inf = 1/0</ |
inf = 1/0</syntaxhighlight> |
||
Test for the two standard floating point types: |
Test for the two standard floating point types: |
||
< |
<syntaxhighlight lang="haskell">*Main> infinity :: Float |
||
Infinity |
Infinity |
||
*Main> infinity :: Double |
*Main> infinity :: Double |
||
Infinity</ |
Infinity</syntaxhighlight> |
||
Or you can simply use division by 0: |
Or you can simply use division by 0: |
||
< |
<syntaxhighlight lang="haskell">Prelude> 1 / 0 :: Float |
||
Infinity |
Infinity |
||
Prelude> 1 / 0 :: Double |
Prelude> 1 / 0 :: Double |
||
Infinity</ |
Infinity</syntaxhighlight> |
||
Or use "read" to read the string representation: |
Or use "read" to read the string representation: |
||
< |
<syntaxhighlight lang="haskell">Prelude> read "Infinity" :: Float |
||
Infinity |
Infinity |
||
Prelude> read "Infinity" :: Double |
Prelude> read "Infinity" :: Double |
||
Infinity</ |
Infinity</syntaxhighlight> |
||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |
||
Line 593: | Line 641: | ||
IDL provides the standard IEEE values for _inf and _NaN in the !Values system structure: |
IDL provides the standard IEEE values for _inf and _NaN in the !Values system structure: |
||
< |
<syntaxhighlight lang="idl">print, !Values.f_infinity ;; for normal floats or |
||
print, !Values.D_infinity ;; for doubles</ |
print, !Values.D_infinity ;; for doubles</syntaxhighlight> |
||
=={{header|Io}}== |
=={{header|Io}}== |
||
< |
<syntaxhighlight lang="io">inf := 1/0</syntaxhighlight> |
||
or |
or |
||
<lang |
<syntaxhighlight lang="io">Number constants inf</syntaxhighlight> |
||
=={{header|IS-BASIC}}== |
=={{header|IS-BASIC}}== |
||
<lang |
<syntaxhighlight lang="is-basic">PRINT INF</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 615: | Line 663: | ||
Example: |
Example: |
||
<syntaxhighlight lang="j"> |
|||
<lang j> |
|||
_ * 5 NB. multiplying infinity to 5 results in infinity |
_ * 5 NB. multiplying infinity to 5 results in infinity |
||
_ |
_ |
||
Line 622: | Line 670: | ||
5 % 0 NB. dividing 5 by 0 results in infinity |
5 % 0 NB. dividing 5 by 0 results in infinity |
||
_ |
_ |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{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>: |
||
< |
<syntaxhighlight lang="java">double infinity = Double.POSITIVE_INFINITY; //defined as 1.0/0.0 |
||
Double.isInfinite(infinity); //true</ |
Double.isInfinite(infinity); //true</syntaxhighlight> |
||
As a function: |
As a function: |
||
< |
<syntaxhighlight lang="java">public static double getInf(){ |
||
return Double.POSITIVE_INFINITY; |
return Double.POSITIVE_INFINITY; |
||
}</ |
}</syntaxhighlight> |
||
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. |
||
< |
<syntaxhighlight lang="java">double biggestNumber = Double.MAX_VALUE;</syntaxhighlight> |
||
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": |
||
<lang |
<syntaxhighlight lang="javascript">Infinity</syntaxhighlight> |
||
as well as constants in the Number class: |
as well as constants in the Number class: |
||
< |
<syntaxhighlight lang="javascript">Number.POSITIVE_INFINITY |
||
Number.NEGATIVE_INFINITY</ |
Number.NEGATIVE_INFINITY</syntaxhighlight> |
||
The global isFinite() function tests for finiteness: |
The global isFinite() function tests for finiteness: |
||
<lang |
<syntaxhighlight lang="javascript">isFinite(x)</syntaxhighlight> |
||
=={{header| |
=={{header|Joy}}== |
||
<syntaxhighlight lang="joy">1 1024 ldexp dup neg stack.</syntaxhighlight> |
|||
jq uses IEEE 754 64-bit floating-point arithmetic, and very large number literals, e.g. 1e1000, are evaluated as IEEE 754 infinity. If your version of jq does not include `infinite` as a built-in, you could therefore define it as follows: |
|||
{{out}} |
|||
<pre>[-inf inf]</pre> |
|||
=={{header|jq}}== |
|||
<lang jq>def infinite: 1e1000;</lang> |
|||
Sufficiently recent versions of the C, Go and Rust implementations of jq (jq, gojq, and jaq, respectively) all allow `infinite` as a scalar value in jq programs; jq and gojq display its value as 1.7976931348623157e+308. The C implementation also allows the token `inf` when reading JSON, and stores it as `infinite`. |
|||
The C implementation of jq uses IEEE 754 64-bit floating-point arithmetic, and very large real number literals, e.g. 1e1000, are evaluated as IEEE 754 infinity, so if your version of jq does not include `infinite` as a built-in, you could therefore define it as follows: |
|||
<lang |
<syntaxhighlight lang="jq">def infinite: 1e1000;</syntaxhighlight> |
||
To test whether a jq value is equal to `infinite` or `- infinite`, one can use the built-in filter `isinfinite`. One can also use `==` in the expected manner. |
|||
Currently, the infinite value prints as though it were a very large floating point number. |
|||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
Julia uses IEEE floating-point arithmetic and includes a built-in constant `Inf` for (64-bit) floating-point infinity. Inf32 can be used as 32-bit infinity, when avoiding type promotions to Int64. |
Julia uses IEEE floating-point arithmetic and includes a built-in constant `Inf` for (64-bit) floating-point infinity. Inf32 can be used as 32-bit infinity, when avoiding type promotions to Int64. |
||
<syntaxhighlight lang="julia"> |
|||
<lang Julia> |
|||
julia> julia> Inf32 == Inf64 == Inf16 == Inf |
julia> julia> Inf32 == Inf64 == Inf16 == Inf |
||
true |
true |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|K}}== |
=={{header|K}}== |
||
K has predefined positive and negative integer and float infinities: -0I, 0I, -0i, 0i. They have following properties: |
K has predefined positive and negative integer and float infinities: -0I, 0I, -0i, 0i. They have following properties: |
||
{{works with|Kona}} |
{{works with|Kona}} |
||
< |
<syntaxhighlight lang="k"> / Integer infinities |
||
/ 0I is just 2147483647 |
/ 0I is just 2147483647 |
||
/ -0I is just -2147483647 |
/ -0I is just -2147483647 |
||
Line 716: | Line 767: | ||
/ but |
/ but |
||
0.0%0.0 |
0.0%0.0 |
||
0.0</ |
0.0</syntaxhighlight> |
||
=={{header|Klingphix}}== |
=={{header|Klingphix}}== |
||
< |
<syntaxhighlight lang="klingphix">1e300 dup mult tostr "inf" equal ["Infinity" print] if |
||
" " input</ |
" " input</syntaxhighlight> |
||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
< |
<syntaxhighlight lang="scala">fun main(args: Array<String>) { |
||
val p = Double.POSITIVE_INFINITY // +∞ |
val p = Double.POSITIVE_INFINITY // +∞ |
||
println(p.isInfinite()) // true |
println(p.isInfinite()) // true |
||
Line 734: | Line 785: | ||
println(n.isFinite()) // false |
println(n.isFinite()) // false |
||
println("${n < 0} ${n > 0}") // true false |
println("${n < 0} ${n > 0}") // true false |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>true |
<pre>true |
||
Line 745: | Line 796: | ||
=={{header|Lambdatalk}}== |
=={{header|Lambdatalk}}== |
||
Lambdatalk is built on Javascript and can inherit lots of its capabilities. For instance: |
Lambdatalk is built on Javascript and can inherit lots of its capabilities. For instance: |
||
< |
<syntaxhighlight lang="scheme"> |
||
{/ 1 0} |
{/ 1 0} |
||
-> Infinity |
-> Infinity |
||
Line 754: | Line 805: | ||
{< {pow 10 1000} Infinity} |
{< {pow 10 1000} Infinity} |
||
-> false |
-> false |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Lasso}}== |
=={{header|Lasso}}== |
||
Lasso supports 64-bit decimals.. This gives Lasso's decimal numbers a range from approximately negative to positive 2x10^300 and with precision down to 2x10^-300. Lasso also supports decimal literals for NaN (not a number) as well and positive and negative infinity. |
Lasso supports 64-bit decimals.. This gives Lasso's decimal numbers a range from approximately negative to positive 2x10^300 and with precision down to 2x10^-300. Lasso also supports decimal literals for NaN (not a number) as well and positive and negative infinity. |
||
< |
<syntaxhighlight lang="lasso">infinity |
||
'<br />' |
'<br />' |
||
infinity -> type</ |
infinity -> type</syntaxhighlight> |
||
-> inf |
-> inf |
||
Line 768: | Line 819: | ||
Lingo stores floats using IEEE 754 double-precision (64-bit) format. |
Lingo stores floats using IEEE 754 double-precision (64-bit) format. |
||
INF is not a constant that can be used programmatically, but only a special return value. |
INF is not a constant that can be used programmatically, but only a special return value. |
||
< |
<syntaxhighlight lang="lingo">x = (1-power(2, -53)) * power(2, 1023) * 2 |
||
put ilk(x), x |
put ilk(x), x |
||
-- #float 1.79769313486232e308 |
-- #float 1.79769313486232e308 |
||
Line 774: | Line 825: | ||
x = (1-power(2, -53)) * power(2, 1023) * 3 |
x = (1-power(2, -53)) * power(2, 1023) * 3 |
||
put ilk(x), x, -x |
put ilk(x), x, -x |
||
-- #float INF -INF</ |
-- #float INF -INF</syntaxhighlight> |
||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
< |
<syntaxhighlight lang="lua"> |
||
function infinity() |
function infinity() |
||
return 1/0 --lua uses unboxed C floats for all numbers |
return 1/0 --lua uses unboxed C floats for all numbers |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|M2000 Interpreter}}== |
=={{header|M2000 Interpreter}}== |
||
<syntaxhighlight lang="m2000 interpreter"> |
|||
<lang M2000 Interpreter> |
|||
Rem : locale 1033 |
Rem : locale 1033 |
||
Module CheckIt { |
Module CheckIt { |
||
Line 832: | Line 883: | ||
} |
} |
||
Checkit |
Checkit |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Maple}}== |
=={{header|Maple}}== |
||
Maple's floating point numerics are a strict extension of IEEE/754 and IEEE/854 so there is already a built-in infinity. (In fact, there are several.) The following procedure just returns the floating point (positive) infinity directly. |
Maple's floating point numerics are a strict extension of IEEE/754 and IEEE/854 so there is already a built-in infinity. (In fact, there are several.) The following procedure just returns the floating point (positive) infinity directly. |
||
<syntaxhighlight lang="maple"> |
|||
<lang Maple> |
|||
> proc() Float(infinity) end(); |
> proc() Float(infinity) end(); |
||
Float(infinity) |
Float(infinity) |
||
</syntaxhighlight> |
|||
</lang> |
|||
There is also an exact infinity ("infinity"), a negative float infinity ("Float(-infinity)" or "-Float(infinity)") and a suite of complex infinities. The next procedure returns a boxed machine (double precision) float infinity. |
There is also an exact infinity ("infinity"), a negative float infinity ("Float(-infinity)" or "-Float(infinity)") and a suite of complex infinities. The next procedure returns a boxed machine (double precision) float infinity. |
||
<syntaxhighlight lang="maple"> |
|||
<lang Maple> |
|||
> proc() HFloat(infinity) end(); |
> proc() HFloat(infinity) end(); |
||
HFloat(infinity) |
HFloat(infinity) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
=={{header|Mathematica}} / {{header|Wolfram Language}}== |
||
Mathematica has infinity built-in as a symbol. Which can be used throughout the software: |
Mathematica has infinity built-in as a symbol. Which can be used throughout the software: |
||
< |
<syntaxhighlight lang="mathematica">Sum[1/n^2,{n,Infinity}] |
||
1/Infinity |
1/Infinity |
||
Integrate[Exp[-x^2], {x, -Infinity, Infinity}] |
Integrate[Exp[-x^2], {x, -Infinity, Infinity}] |
||
10^100 < Infinity</ |
10^100 < Infinity</syntaxhighlight> |
||
gives back: |
gives back: |
||
<pre>Pi^2/6 |
<pre>Pi^2/6 |
||
Line 858: | Line 909: | ||
True</pre> |
True</pre> |
||
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]]: |
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]]: |
||
< |
<syntaxhighlight lang="mathematica">Integrate[Exp[-x^2]/(x^2 - 1), {x, 0, DirectedInfinity[Exp[I Pi/4]]}]</syntaxhighlight> |
||
gives back: |
gives back: |
||
<pre>-((Pi (I+Erfi[1]))/(2 E))</pre> |
<pre>-((Pi (I+Erfi[1]))/(2 E))</pre> |
||
Line 865: | Line 916: | ||
MATLAB implements the IEEE 754 floating point standard as the default for all numeric data types. +Inf and -Inf are by default implemented and supported by MATLAB. To check if a variable has the value +/-Inf, one can use the built-in function "isinf()" which will return a Boolean 1 if the number is +/-inf. |
MATLAB implements the IEEE 754 floating point standard as the default for all numeric data types. +Inf and -Inf are by default implemented and supported by MATLAB. To check if a variable has the value +/-Inf, one can use the built-in function "isinf()" which will return a Boolean 1 if the number is +/-inf. |
||
< |
<syntaxhighlight lang="matlab">a = +Inf; |
||
isinf(a) |
isinf(a) |
||
</syntaxhighlight> |
|||
</lang> |
|||
Returns: |
Returns: |
||
Line 876: | Line 927: | ||
=={{header|Maxima}}== |
=={{header|Maxima}}== |
||
< |
<syntaxhighlight lang="maxima">/* Maxima has inf (positive infinity) and minf (negative infinity) */ |
||
declare(x, real)$ |
declare(x, real)$ |
||
Line 889: | Line 940: | ||
1.0/0.0; |
1.0/0.0; |
||
/* expt: undefined: 0 to a negative exponent. |
/* expt: undefined: 0 to a negative exponent. |
||
-- an error. To debug this try: debugmode(true); */</ |
-- an error. To debug this try: debugmode(true); */</syntaxhighlight> |
||
=={{header|Metafont}}== |
=={{header|Metafont}}== |
||
Line 895: | Line 946: | ||
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 |
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 |
||
< |
<syntaxhighlight lang="metafont">infinity := 4095.99998;</syntaxhighlight> |
||
=={{header|MiniScript}}== |
=={{header|MiniScript}}== |
||
MiniScript uses IEEE numerics, so: |
MiniScript uses IEEE numerics, so: |
||
< |
<syntaxhighlight lang="miniscript">posInfinity = 1/0 |
||
print posInfinity</ |
print posInfinity</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>INF</pre> |
<pre>INF</pre> |
||
=={{header|Modula-2}}== |
=={{header|Modula-2}}== |
||
< |
<syntaxhighlight lang="modula-2">MODULE inf; |
||
IMPORT InOut; |
IMPORT InOut; |
||
Line 913: | Line 964: | ||
InOut.WriteReal (1.0 / 0.0, 12, 12); |
InOut.WriteReal (1.0 / 0.0, 12, 12); |
||
InOut.WriteLn |
InOut.WriteLn |
||
END inf.</ |
END inf.</syntaxhighlight> |
||
Producing |
Producing |
||
< |
<syntaxhighlight lang="modula-2">jan@Beryllium:~/modula/rosetta$ inf |
||
**** RUNTIME ERROR bound check error |
**** RUNTIME ERROR bound check error |
||
Floating point exception</ |
Floating point exception</syntaxhighlight> |
||
=={{header|Modula-3}}== |
=={{header|Modula-3}}== |
||
Line 924: | Line 975: | ||
If the implementation doesn't support IEEE floats, the program prints arbitrary values (Critical Mass Modula-3 implementation does support IEEE floats). |
If the implementation doesn't support IEEE floats, the program prints arbitrary values (Critical Mass Modula-3 implementation does support IEEE floats). |
||
< |
<syntaxhighlight lang="modula3">MODULE Inf EXPORTS Main; |
||
IMPORT IO, IEEESpecial; |
IMPORT IO, IEEESpecial; |
||
Line 931: | Line 982: | ||
IO.PutReal(IEEESpecial.RealPosInf); |
IO.PutReal(IEEESpecial.RealPosInf); |
||
IO.Put("\n"); |
IO.Put("\n"); |
||
END Inf.</ |
END Inf.</syntaxhighlight> |
||
Output: |
Output: |
||
Line 940: | Line 991: | ||
=={{header|Nemerle}}== |
=={{header|Nemerle}}== |
||
Both single and double precision floating point numbers support PositiveInfinity, NegativeInfinity and NaN. |
Both single and double precision floating point numbers support PositiveInfinity, NegativeInfinity and NaN. |
||
< |
<syntaxhighlight lang="nemerle">def posinf = double.PositiveInfinity; |
||
def a = IsInfinity(posinf); // a = true |
def a = IsInfinity(posinf); // a = true |
||
def b = IsNegativeInfinity(posinf); // b = false |
def b = IsNegativeInfinity(posinf); // b = false |
||
def c = IsPositiveInfinity(posinf); // c = true</ |
def c = IsPositiveInfinity(posinf); // c = true</syntaxhighlight> |
||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
<lang |
<syntaxhighlight lang="nim">Inf</syntaxhighlight> |
||
is a predefined constant in Nim: |
is a predefined constant in Nim: |
||
< |
<syntaxhighlight lang="nim">var f = Inf |
||
echo f</ |
echo f</syntaxhighlight> |
||
=={{header|NS-HUBASIC}}== |
=={{header|NS-HUBASIC}}== |
||
<lang |
<syntaxhighlight lang="ns-hubasic">10 PRINT 1/0</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
?DZ ERROR is a division by zero error in NS-HUBASIC. |
?DZ ERROR is a division by zero error in NS-HUBASIC. |
||
Line 960: | Line 1,011: | ||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
<lang |
<syntaxhighlight lang="ocaml">infinity</syntaxhighlight> |
||
is already a pre-defined value in OCaml. |
is already a pre-defined value in OCaml. |
||
Line 972: | Line 1,023: | ||
=={{header|Oforth}}== |
=={{header|Oforth}}== |
||
< |
<syntaxhighlight lang="oforth">10 1000.0 powf dup println dup neg println 1 swap / println</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 987: | Line 1,038: | ||
-inf.0 ; negative infinity |
-inf.0 ; negative infinity |
||
< |
<syntaxhighlight lang="scheme"> |
||
(define (infinite? x) (or (equal? x +inf.0) (equal? x -inf.0))) |
(define (infinite? x) (or (equal? x +inf.0) (equal? x -inf.0))) |
||
Line 996: | Line 1,047: | ||
(infinite? 1/3456) ==> #false |
(infinite? 1/3456) ==> #false |
||
(infinite? 17+28i) ==> #false |
(infinite? 17+28i) ==> #false |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|OpenEdge/Progress}}== |
=={{header|OpenEdge/Progress}}== |
||
Line 1,002: | Line 1,053: | ||
The unknown value (represented by a question mark) can be considered to equal infinity. There is no difference between positive and negative infinity but the unknown value sometimes sorts low and sometimes sorts high when used in queries. |
The unknown value (represented by a question mark) can be considered to equal infinity. There is no difference between positive and negative infinity but the unknown value sometimes sorts low and sometimes sorts high when used in queries. |
||
< |
<syntaxhighlight lang="progress">MESSAGE |
||
1.0 / 0.0 SKIP |
1.0 / 0.0 SKIP |
||
-1.0 / 0.0 SKIP(1) |
-1.0 / 0.0 SKIP(1) |
||
( 1.0 / 0.0 ) = ( -1.0 / 0.0 ) |
( 1.0 / 0.0 ) = ( -1.0 / 0.0 ) |
||
VIEW-AS ALERT-BOX.</ |
VIEW-AS ALERT-BOX.</syntaxhighlight> |
||
Output |
Output |
||
Line 1,023: | Line 1,074: | ||
=={{header|OxygenBasic}}== |
=={{header|OxygenBasic}}== |
||
Using double precision floats: |
Using double precision floats: |
||
< |
<syntaxhighlight lang="oxygenbasic"> |
||
print 1.5e-400 '0 |
print 1.5e-400 '0 |
||
Line 1,044: | Line 1,095: | ||
print f '#-INF |
print f '#-INF |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Oz}}== |
=={{header|Oz}}== |
||
< |
<syntaxhighlight lang="oz">declare |
||
PosInf = 1./0. |
PosInf = 1./0. |
||
NegInf = ~1./0. |
NegInf = ~1./0. |
||
Line 1,059: | Line 1,110: | ||
PosInf * PosInf = PosInf |
PosInf * PosInf = PosInf |
||
PosInf * NegInf = NegInf |
PosInf * NegInf = NegInf |
||
NegInf * NegInf = PosInf</ |
NegInf * NegInf = PosInf</syntaxhighlight> |
||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
{{works with|PARI/GP|version 2.8.0 and higher}} |
{{works with|PARI/GP|version 2.8.0 and higher}} |
||
<lang |
<syntaxhighlight lang="parigp">+oo</syntaxhighlight> |
||
{{works with|PARI/GP|version 2.2.9 to 2.7.0}} |
{{works with|PARI/GP|version 2.2.9 to 2.7.0}} |
||
< |
<syntaxhighlight lang="parigp">infty()={ |
||
[1] \\ Used for many functions like intnum |
[1] \\ Used for many functions like intnum |
||
};</ |
};</syntaxhighlight> |
||
=={{header|Pascal}}== |
=={{header|Pascal}}== |
||
See [[Infinity#Delphi | Delphi]] |
See [[Infinity#Delphi | Delphi]] |
||
=={{header|PascalABC.NET}}== |
|||
<syntaxhighlight lang="delphi"> |
|||
## |
|||
Write(real.PositiveInfinity); |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Infinity |
|||
</pre> |
|||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
Positive infinity: |
Positive infinity: |
||
< |
<syntaxhighlight lang="perl">my $x = 0 + "inf"; |
||
my $y = 0 + "+inf";</ |
my $y = 0 + "+inf";</syntaxhighlight> |
||
Negative infinity: |
Negative infinity: |
||
< |
<syntaxhighlight lang="perl">my $x = 0 - "inf"; |
||
my $y = 0 + "-inf";</ |
my $y = 0 + "-inf";</syntaxhighlight> |
||
The "<code>0 + </code>..." is used here to make sure that the variable stores a value that is actually an infinitive number instead of just a string <code>"inf"</code> but in practice one can use just: |
The "<code>0 + </code>..." is used here to make sure that the variable stores a value that is actually an infinitive number instead of just a string <code>"inf"</code> but in practice one can use just: |
||
< |
<syntaxhighlight lang="perl">my $x = "inf";</syntaxhighlight> |
||
and <code>$x</code> while originally holding a string will get converted to an infinite number when it is first used as a number. |
and <code>$x</code> while originally holding a string will get converted to an infinite number when it is first used as a number. |
||
Some programmers use expressions that overflow the IEEE floating point numbers such as: |
Some programmers use expressions that overflow the IEEE floating point numbers such as: |
||
< |
<syntaxhighlight lang="perl">my $x = 1e1000;</syntaxhighlight> |
||
which is 10<sup>1000</sup> or googol<sup>10</sup> or even numbers like this one: |
which is 10<sup>1000</sup> or googol<sup>10</sup> or even numbers like this one: |
||
< |
<syntaxhighlight lang="perl">my $y = 10**10**10;</syntaxhighlight> |
||
which is 10<sup>10000000000</sup> but it has to make some assumptions about the underlying hardware format and its size. Furthermore, using such literals in the scope of some pragmas such as <code>bigint</code>, <code>bignum</code> or <code>bigrat</code> would actually compute those numbers: |
which is 10<sup>10000000000</sup> but it has to make some assumptions about the underlying hardware format and its size. Furthermore, using such literals in the scope of some pragmas such as <code>bigint</code>, <code>bignum</code> or <code>bigrat</code> would actually compute those numbers: |
||
< |
<syntaxhighlight lang="perl">use bigint; |
||
my $x = 1e1000; |
my $x = 1e1000; |
||
my $y = 10**10**10; # N.B. this will consume vast quantities of RAM</ |
my $y = 10**10**10; # N.B. this will consume vast quantities of RAM</syntaxhighlight> |
||
Here the <code>$x</code> and <code>$y</code> when printed would give 1001 and 10000000001-digit numbers respectively, the latter taking no less than 10GB of space to just output. |
Here the <code>$x</code> and <code>$y</code> when printed would give 1001 and 10000000001-digit numbers respectively, the latter taking no less than 10GB of space to just output. |
||
Under those pragmas, however, there is a simpler way to use infinite values, thanks to the <code>inf</code> symbol being exported into the namespace by default: |
Under those pragmas, however, there is a simpler way to use infinite values, thanks to the <code>inf</code> symbol being exported into the namespace by default: |
||
< |
<syntaxhighlight lang="perl">use bigint; |
||
my $x = inf; |
my $x = inf; |
||
my $y = -inf;</ |
my $y = -inf;</syntaxhighlight> |
||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
<!--< |
<!--<syntaxhighlight lang="phix">(phixonline)--> |
||
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
||
<span style="color: #008080;">constant</span> <span style="color: #000000;">infinity</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1e300</span><span style="color: #0000FF;">*</span><span style="color: #000000;">1e300</span> |
<span style="color: #008080;">constant</span> <span style="color: #000000;">infinity</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1e300</span><span style="color: #0000FF;">*</span><span style="color: #000000;">1e300</span> |
||
<span style="color: #0000FF;">?</span> <span style="color: #000000;">infinity</span> |
<span style="color: #0000FF;">?</span> <span style="color: #000000;">infinity</span> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
{{out}} |
{{out}} |
||
desktop/Phix: |
desktop/Phix: |
||
Line 1,117: | Line 1,181: | ||
=={{header|Phixmonti}}== |
=={{header|Phixmonti}}== |
||
< |
<syntaxhighlight lang="phixmonti">1e300 dup * tostr "inf" == if "Infinity" print endif</syntaxhighlight> |
||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
This is how you get infinity: |
This is how you get infinity: |
||
<lang |
<syntaxhighlight lang="php">INF</syntaxhighlight> |
||
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 1,132: | Line 1,196: | ||
support (scaled bignum arithmetics), but some functions return 'T' for infinite |
support (scaled bignum arithmetics), but some functions return 'T' for infinite |
||
results. |
results. |
||
< |
<syntaxhighlight lang="picolisp">(load "@lib/math.l") |
||
: (exp 1000.0) |
: (exp 1000.0) |
||
-> T</ |
-> T</syntaxhighlight> |
||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
<syntaxhighlight lang="pl/i"> |
|||
<lang PL/I> |
|||
declare x float, y float (15), z float (18); |
declare x float, y float (15), z float (18); |
||
put skip list (huge(x), huge(y), huge(z)); |
put skip list (huge(x), huge(y), huge(z)); |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|PostScript}}== |
=={{header|PostScript}}== |
||
< |
<syntaxhighlight lang="postscript">/infinity { 9 99 exp } def</syntaxhighlight> |
||
=={{header|PowerShell}}== |
=={{header|PowerShell}}== |
||
A .NET floating-point number representing infinity is available. |
A .NET floating-point number representing infinity is available. |
||
< |
<syntaxhighlight lang="powershell">function infinity { |
||
[double]::PositiveInfinity |
[double]::PositiveInfinity |
||
}</ |
}</syntaxhighlight> |
||
=={{header|PureBasic}}== |
=={{header|PureBasic}}== |
||
Line 1,157: | Line 1,221: | ||
PureBasic uses [[wp:IEEE_754-2008|IEEE 754]] coding for float types. PureBasic also includes the function <tt>Infinity()</tt> that return the positive value for infinity and the boolean function <tt>IsInfinite(value.f)</tt> that returns true if the floating point value is either positive or negative infinity. |
PureBasic uses [[wp:IEEE_754-2008|IEEE 754]] coding for float types. PureBasic also includes the function <tt>Infinity()</tt> that return the positive value for infinity and the boolean function <tt>IsInfinite(value.f)</tt> that returns true if the floating point value is either positive or negative infinity. |
||
< |
<syntaxhighlight lang="purebasic">If OpenConsole() |
||
Define.d a, b |
Define.d a, b |
||
b = 0 |
b = 0 |
||
Line 1,176: | Line 1,240: | ||
CloseConsole() |
CloseConsole() |
||
EndIf |
EndIf |
||
</syntaxhighlight> |
|||
</lang> |
|||
''Outputs'' |
''Outputs'' |
||
Line 1,186: | Line 1,250: | ||
=={{header|Python}}== |
=={{header|Python}}== |
||
This is how you get infinity: |
This is how you get infinity: |
||
< |
<syntaxhighlight lang="python">>>> float('infinity') |
||
inf</ |
inf</syntaxhighlight> |
||
''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.'' <br> |
''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.'' <br> |
||
''The Decimal module explicitly supports +/-infinity Nan, +/-0.0, etc without exception.'' |
''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: |
Floating-point division by 0 doesn't give you infinity, it raises an exception: |
||
< |
<syntaxhighlight lang="python">>>> 1.0 / 0.0 |
||
Traceback (most recent call last): |
Traceback (most recent call last): |
||
File "<stdin>", line 1, in <module> |
File "<stdin>", line 1, in <module> |
||
ZeroDivisionError: float division</ |
ZeroDivisionError: float division</syntaxhighlight> |
||
If <tt>float('infinity')</tt> doesn't work on your platform, you could use this trick: |
If <tt>float('infinity')</tt> doesn't work on your platform, you could use this trick: |
||
Line 1,203: | Line 1,267: | ||
=={{header|QB64}}== |
=={{header|QB64}}== |
||
< |
<syntaxhighlight lang="c++">#include<math.h> |
||
//save as inf.h |
//save as inf.h |
||
double inf(void){ |
double inf(void){ |
||
return HUGE_VAL; |
return HUGE_VAL; |
||
}</ |
}</syntaxhighlight> |
||
< |
<syntaxhighlight lang="vb">Declare CustomType Library "inf" |
||
Function inf# |
Function inf# |
||
End Declare |
End Declare |
||
Print inf</ |
Print inf</syntaxhighlight> |
||
=={{header|QBasic}}== |
|||
{{works with|QBasic|1.1}} |
|||
<syntaxhighlight lang="qbasic">DECLARE FUNCTION f! () |
|||
ON ERROR GOTO TratoError |
|||
PRINT 0! |
|||
PRINT 0 / -1.5 |
|||
PRINT 1.5 / 0 |
|||
PRINT 0 / 0 |
|||
PRINT f |
|||
END |
|||
TratoError: |
|||
PRINT "Error "; ERR; " on line "; ERL; CHR$(9); " --> "; |
|||
SELECT CASE ERR |
|||
CASE 6 |
|||
PRINT "Overflow" |
|||
RESUME NEXT |
|||
CASE 11 |
|||
PRINT "Division by zero" |
|||
RESUME NEXT |
|||
CASE ELSE |
|||
PRINT "Unexpected error, ending program." |
|||
END |
|||
END SELECT |
|||
FUNCTION f! |
|||
f! = -1.5 / 0 |
|||
END FUNCTION</syntaxhighlight> |
|||
=={{header|R}}== |
=={{header|R}}== |
||
< |
<syntaxhighlight lang="r"> Inf #positive infinity |
||
-Inf #negative infinity |
-Inf #negative infinity |
||
.Machine$double.xmax # largest finite floating-point number |
.Machine$double.xmax # largest finite floating-point number |
||
Line 1,225: | Line 1,320: | ||
forcefinite(c(1, -1, 0, .Machine$double.xmax, -.Machine$double.xmax, Inf, -Inf)) |
forcefinite(c(1, -1, 0, .Machine$double.xmax, -.Machine$double.xmax, Inf, -Inf)) |
||
# [1] 1.000000e+00 -1.000000e+00 0.000000e+00 1.797693e+308 |
# [1] 1.000000e+00 -1.000000e+00 0.000000e+00 1.797693e+308 |
||
# [5] -1.797693e+308 1.797693e+308 -1.797693e+308</ |
# [5] -1.797693e+308 1.797693e+308 -1.797693e+308</syntaxhighlight> |
||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
Line 1,231: | Line 1,326: | ||
as in Scheme: |
as in Scheme: |
||
< |
<syntaxhighlight lang="racket">#lang racket |
||
+inf.0 ; positive infinity |
+inf.0 ; positive infinity |
||
(define (finite? x) (< -inf.0 x +inf.0)) |
(define (finite? x) (< -inf.0 x +inf.0)) |
||
(define (infinite? x) (not (finite? x)))</ |
(define (infinite? x) (not (finite? x)))</syntaxhighlight> |
||
=={{header|Raku}}== |
=={{header|Raku}}== |
||
(formerly Perl 6) |
(formerly Perl 6) |
||
Inf support is required by language spec on all abstract Numeric types (in the absence of subset constraints) including Num, Rat and Int types. Native integers cannot support Inf, so attempting to assign Inf will result in an exception; native floats are expected to follow IEEE standards including +/- Inf and NaN. |
Inf support is required by language spec on all abstract Numeric types (in the absence of subset constraints) including Num, Rat and Int types. Native integers cannot support Inf, so attempting to assign Inf will result in an exception; native floats are expected to follow IEEE standards including +/- Inf and NaN. |
||
<lang |
<syntaxhighlight lang="raku" line>my $x = 1.5/0; # Failure: catchable error, if evaluated will return: "Attempt to divide by zero ... |
||
my $y = (1.5/0).Num; # assigns 'Inf'</ |
my $y = (1.5/0).Num; # assigns 'Inf'</syntaxhighlight> |
||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
Line 1,282: | Line 1,377: | ||
=={{header|RLaB}}== |
=={{header|RLaB}}== |
||
<syntaxhighlight lang="rlab"> |
|||
<lang RLaB> |
|||
>> x = inf() |
>> x = inf() |
||
inf |
inf |
||
Line 1,291: | Line 1,386: | ||
>> -inf() > 10 |
>> -inf() > 10 |
||
0 |
0 |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|RPL}}== |
|||
{{in}} |
|||
<pre> |
|||
MAXR →NUM |
|||
</pre> |
|||
{{out}} |
|||
<pre> |
|||
1: 1.7976931348E+308 |
|||
</pre> |
|||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
Infinity is a Float value |
Infinity is a Float value |
||
< |
<syntaxhighlight lang="ruby">a = 1.0/0 # => Infinity |
||
a.finite? # => false |
a.finite? # => false |
||
a.infinite? # => 1 |
a.infinite? # => 1 |
||
Line 1,304: | Line 1,408: | ||
a = Float::MAX # => 1.79769313486232e+308 |
a = Float::MAX # => 1.79769313486232e+308 |
||
a.finite? # => true |
a.finite? # => true |
||
a.infinite? # => nil</ |
a.infinite? # => nil</syntaxhighlight> |
||
{{works with|Ruby|1.9.2+}} |
{{works with|Ruby|1.9.2+}} |
||
< |
<syntaxhighlight lang="ruby">a = Float::INFINITY # => Infinity</syntaxhighlight> |
||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
Rust has builtin function for floating types which returns infinity. This program outputs 'inf'. |
Rust has builtin function for floating types which returns infinity. This program outputs 'inf'. |
||
< |
<syntaxhighlight lang="rust">fn main() { |
||
let inf = f32::INFINITY; |
let inf = f32::INFINITY; |
||
println!("{}", inf); |
println!("{}", inf); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
Line 1,321: | Line 1,425: | ||
* [[Extreme_floating_point_values#Scala]] |
* [[Extreme_floating_point_values#Scala]] |
||
In order to be compliant with IEEE-754, Scala has all support for infinity on its floating-point types (<tt>float</tt>, <tt>double</tt>). You can get infinity from constants in the corresponding wrapper class; for example, <tt>Double</tt>: |
In order to be compliant with IEEE-754, Scala has all support for infinity on its floating-point types (<tt>float</tt>, <tt>double</tt>). You can get infinity from constants in the corresponding wrapper class; for example, <tt>Double</tt>: |
||
< |
<syntaxhighlight lang="scala">val inf = Double.PositiveInfinity //defined as 1.0/0.0 |
||
inf.isInfinite; //true</ |
inf.isInfinite; //true</syntaxhighlight> |
||
The largest possible number in Scala (without using the <tt>Big</tt> classes) is also in the <tt>Double</tt> class. |
The largest possible number in Scala (without using the <tt>Big</tt> classes) is also in the <tt>Double</tt> class. |
||
< |
<syntaxhighlight lang="scala">val biggestNumber = Double.MaxValue</syntaxhighlight> |
||
REPL session: |
REPL session: |
||
< |
<syntaxhighlight lang="scala">scala> 1 / 0. |
||
res2: Double = Infinity |
res2: Double = Infinity |
||
Line 1,337: | Line 1,441: | ||
scala> 1 / Double.NegativeInfinity |
scala> 1 / Double.NegativeInfinity |
||
res5: Double = -0.0</ |
res5: Double = -0.0</syntaxhighlight> |
||
=={{header|Scheme}}== |
=={{header|Scheme}}== |
||
< |
<syntaxhighlight lang="scheme">+inf.0 ; positive infinity |
||
(define (finite? x) (< -inf.0 x +inf.0)) |
(define (finite? x) (< -inf.0 x +inf.0)) |
||
(define (infinite? x) (not (finite? x)))</ |
(define (infinite? x) (not (finite? x)))</syntaxhighlight> |
||
=={{header|Seed7}}== |
=={{header|Seed7}}== |
||
Line 1,348: | Line 1,452: | ||
The library [http://seed7.sourceforge.net/libraries/float.htm float.s7i] defines |
The library [http://seed7.sourceforge.net/libraries/float.htm float.s7i] defines |
||
the constant [http://seed7.sourceforge.net/libraries/float.htm#Infinity Infinity] as: |
the constant [http://seed7.sourceforge.net/libraries/float.htm#Infinity Infinity] as: |
||
< |
<syntaxhighlight lang="seed7">const float: Infinity is 1.0 / 0.0;</syntaxhighlight> |
||
Checks for infinity can be done by comparing with this constant. |
Checks for infinity can be done by comparing with this constant. |
||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
< |
<syntaxhighlight lang="ruby">var a = 1.5/0 # Inf |
||
say a.is_inf # true |
say a.is_inf # true |
||
say a.is_pos # true |
say a.is_pos # true |
||
Line 1,362: | Line 1,466: | ||
var inf = Inf |
var inf = Inf |
||
var ninf = -Inf |
var ninf = -Inf |
||
say (inf == -ninf) # true</ |
say (inf == -ninf) # true</syntaxhighlight> |
||
=={{header|Slate}}== |
=={{header|Slate}}== |
||
<lang |
<syntaxhighlight lang="slate">PositiveInfinity</syntaxhighlight> |
||
=={{header|Smalltalk}}== |
=={{header|Smalltalk}}== |
||
Line 1,379: | Line 1,483: | ||
{{works with|Smalltalk/X}} |
{{works with|Smalltalk/X}} |
||
The behavior is slightly different, in that an exception is raised if you divide by zero: |
The behavior is slightly different, in that an exception is raised if you divide by zero: |
||
< |
<syntaxhighlight lang="smalltalk">FloatD infinity -> INF |
||
1.0 / 0.0 -> "ZeroDivide exception"</ |
1.0 / 0.0 -> "ZeroDivide exception"</syntaxhighlight> |
||
but we can simulate the other behavior with: |
but we can simulate the other behavior with: |
||
< |
<syntaxhighlight lang="smalltalk">[ |
||
1.0 / 0.0 |
1.0 / 0.0 |
||
] on: ZeroDivide do:[:ex | |
] on: ZeroDivide do:[:ex | |
||
ex proceedWith: (FloatD infinity) |
ex proceedWith: (FloatD infinity) |
||
] |
] |
||
-> INF</ |
-> INF</syntaxhighlight> |
||
=={{header|Standard ML}}== |
=={{header|Standard ML}}== |
||
<lang |
<syntaxhighlight lang="sml">Real.posInf</syntaxhighlight> |
||
<pre> |
<pre> |
||
Line 1,401: | Line 1,505: | ||
=={{header|Swift}}== |
=={{header|Swift}}== |
||
Swift's floating-point types (<tt>Float</tt>, <tt>Double</tt>, and any other type that conforms to the <tt>FloatingPointNumber</tt> protocol) all support infinity. You can get infinity from the <tt>infinity</tt> class property in the type: |
Swift's floating-point types (<tt>Float</tt>, <tt>Double</tt>, and any other type that conforms to the <tt>FloatingPointNumber</tt> protocol) all support infinity. You can get infinity from the <tt>infinity</tt> class property in the type: |
||
< |
<syntaxhighlight lang="swift">let inf = Double.infinity |
||
inf.isInfinite //true</ |
inf.isInfinite //true</syntaxhighlight> |
||
As a function: |
As a function: |
||
< |
<syntaxhighlight lang="swift">func getInf() -> Double { |
||
return Double.infinity |
return Double.infinity |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
Line 1,412: | Line 1,516: | ||
Tcl 8.5 has Infinite as a floating point value, not an integer value |
Tcl 8.5 has Infinite as a floating point value, not an integer value |
||
< |
<syntaxhighlight lang="tcl">package require Tcl 8.5 |
||
expr {1.0 / 0} ;# ==> Inf |
expr {1.0 / 0} ;# ==> Inf |
||
expr {-1.0 / 0} ;# ==> -Inf |
expr {-1.0 / 0} ;# ==> -Inf |
||
expr {inf} ;# ==> Inf |
expr {inf} ;# ==> Inf |
||
expr {1 / 0} ;# ==> "divide by zero" error; Inf not part of range of integer division</ |
expr {1 / 0} ;# ==> "divide by zero" error; Inf not part of range of integer division</syntaxhighlight> |
||
A maximal integer is not easy to find, as Tcl switches to unbounded integers when a 64-bit integer is about to roll over: |
A maximal integer is not easy to find, as Tcl switches to unbounded integers when a 64-bit integer is about to roll over: |
||
< |
<syntaxhighlight lang="tcl">% format %lx -1 ;# all bits set |
||
ffffffffffffffff |
ffffffffffffffff |
||
Line 1,430: | Line 1,534: | ||
% incr ii |
% incr ii |
||
9223372036854775808 ;# silently upgrade to unbounded integer, still positive</ |
9223372036854775808 ;# silently upgrade to unbounded integer, still positive</syntaxhighlight> |
||
A theoretical MAXINT, though very impractical, could be |
A theoretical MAXINT, though very impractical, could be |
||
string repeat 9 [expr 2**32-1] |
string repeat 9 [expr 2**32-1] |
||
Line 1,436: | Line 1,540: | ||
=={{header|TI-89 BASIC}}== |
=={{header|TI-89 BASIC}}== |
||
<lang |
<syntaxhighlight lang="ti89b">∞</syntaxhighlight> |
||
=={{header|TorqueScript}}== |
=={{header|TorqueScript}}== |
||
< |
<syntaxhighlight lang="torquescript">function infinity() |
||
{ |
{ |
||
return 1/0; |
return 1/0; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Trith}}== |
=={{header|Trith}}== |
||
The following functions are included as part of the core operators: |
The following functions are included as part of the core operators: |
||
< |
<syntaxhighlight lang="trith"> |
||
: inf 1.0 0.0 / ; |
: inf 1.0 0.0 / ; |
||
: -inf inf neg ; |
: -inf inf neg ; |
||
: inf? abs inf = ; |
: inf? abs inf = ; |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Ursa}}== |
=={{header|Ursa}}== |
||
Infinity is a defined value in Ursa. |
Infinity is a defined value in Ursa. |
||
< |
<syntaxhighlight lang="ursa">decl double d |
||
set d Infinity</ |
set d Infinity</syntaxhighlight> |
||
=={{header|Ursala}}== |
=={{header|Ursala}}== |
||
Line 1,464: | Line 1,568: | ||
< |
<syntaxhighlight lang="ursala">#import flo |
||
infinity = inf!</ |
infinity = inf!</syntaxhighlight> |
||
=={{header|Visual Basic}}== |
=={{header|Visual Basic}}== |
||
Line 1,476: | Line 1,580: | ||
Positive infinity, negative infinity and indefinite number (usable as NaN) can be generated by deliberately dividing by zero under the influence of <code>On Error Resume Next</code>: |
Positive infinity, negative infinity and indefinite number (usable as NaN) can be generated by deliberately dividing by zero under the influence of <code>On Error Resume Next</code>: |
||
< |
<syntaxhighlight lang="vb">Option Explicit |
||
Private Declare Sub GetMem8 Lib "msvbvm60.dll" _ |
Private Declare Sub GetMem8 Lib "msvbvm60.dll" _ |
||
Line 1,502: | Line 1,606: | ||
DoubleAsHex = Right$(String$(8, "0") & Hex$(l(1)), 8) _ |
DoubleAsHex = Right$(String$(8, "0") & Hex$(l(1)), 8) _ |
||
& Right$(String$(8, "0") & Hex$(l(0)), 8) |
& Right$(String$(8, "0") & Hex$(l(0)), 8) |
||
End Function</ |
End Function</syntaxhighlight> |
||
{{out}}<pre>PlusInfinity = 1,#INF (7FF0000000000000) |
{{out}}<pre>PlusInfinity = 1,#INF (7FF0000000000000) |
||
MinusInfinity = -1,#INF (FFF0000000000000) |
MinusInfinity = -1,#INF (FFF0000000000000) |
||
IndefiniteNumber = -1,#IND (FFF8000000000000) |
IndefiniteNumber = -1,#IND (FFF8000000000000) |
||
</pre> |
</pre> |
||
=={{header|V (Vlang)}}== |
|||
<syntaxhighlight lang="v (vlang)">import math |
|||
fn main() { |
|||
mut x := 1.5 // type of x determined by literal |
|||
// that this compiles demonstrates that PosInf returns same type as x, |
|||
// the type specified by the task. |
|||
x = math.inf(1) |
|||
println('$x ${math.is_inf(x, 1)}') // demonstrate result |
|||
}</syntaxhighlight> |
|||
=={{header|Wren}}== |
=={{header|Wren}}== |
||
Wren certainly supports infinity for floating point numbers as we already have a method ''Num.isInfinity'' to test for it. |
Wren certainly supports infinity for floating point numbers as we already have a method ''Num.isInfinity'' to test for it. |
||
< |
<syntaxhighlight lang="wren">var x = 1.5 |
||
var y = x / 0 |
var y = x / 0 |
||
System.print("x = %(x)") |
System.print("x = %(x)") |
||
System.print("y = %(y)") |
System.print("y = %(y)") |
||
System.print("'x' is infinite? %(x.isInfinity)") |
System.print("'x' is infinite? %(x.isInfinity)") |
||
System.print("'y' is infinite? %(y.isInfinity)")</ |
System.print("'y' is infinite? %(y.isInfinity)")</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,527: | Line 1,642: | ||
=={{header|XPL0}}== |
=={{header|XPL0}}== |
||
The IEEE 754 floating point standard is used. |
The IEEE 754 floating point standard is used. |
||
< |
<syntaxhighlight lang="xpl0">int A; |
||
real X; |
real X; |
||
[Format(0, 15); \output in scientific notation |
[Format(0, 15); \output in scientific notation |
||
Line 1,534: | Line 1,649: | ||
A(1):= $7FEF_FFFF; |
A(1):= $7FEF_FFFF; |
||
RlOut(0, X); \display it |
RlOut(0, X); \display it |
||
]</ |
]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,542: | Line 1,657: | ||
=={{header|Yabasic}}== |
=={{header|Yabasic}}== |
||
< |
<syntaxhighlight lang="yabasic">infinity = 1e300*1e300 |
||
if str$(infinity) = "inf" print "Infinity"</ |
if str$(infinity) = "inf" print "Infinity"</syntaxhighlight> |
||
=={{header|Zig}}== |
=={{header|Zig}}== |
||
<lang zig>const std = @import("std"); |
|||
'''Works with:''' 0.10.x, 0.11.x, 0.12.0-dev.1577+9ad03b628 |
|||
const debug = std.debug; |
|||
const math = std.math; |
|||
Assumes that defaul float optimization mode was not changed via @setFloatMode (performed in Strict mode, not Optimized, latter is equivalent to -ffast-math). |
|||
test "infinity" { |
|||
const infinite_f16 = math.inf(f16); |
|||
const infinite_f32 = math.inf(f32); |
|||
const infinite_f64 = math.inf(f64); |
|||
const infinite_f128 = math.inf(f128); |
|||
<syntaxhighlight lang="zig">const std = @import("std"); |
|||
// Any other types besides these four floating types are not implemented. |
|||
const math = std.math; |
|||
debug.assert(math.isInf(infinite_f16)); |
|||
debug.assert(math.isInf(infinite_f32)); |
|||
debug.assert(math.isInf(infinite_f64)); |
|||
debug.assert(math.isInf(infinite_f128)); |
|||
test "infinity" { |
|||
debug.assert(math.isPositiveInf(infinite_f16)); |
|||
const expect = std.testing.expect; |
|||
debug.assert(math.isPositiveInf(infinite_f32)); |
|||
debug.assert(math.isPositiveInf(infinite_f64)); |
|||
debug.assert(math.isPositiveInf(infinite_f128)); |
|||
const float_types = [_]type{ f16, f32, f64, f80, f128, c_longdouble }; |
|||
debug.assert(math.isNegativeInf(-infinite_f16)); |
|||
inline for (float_types) |T| { |
|||
debug.assert(math.isNegativeInf(-infinite_f32)); |
|||
const infinite_value: T = comptime std.math.inf(T); |
|||
debug.assert(math.isNegativeInf(-infinite_f64)); |
|||
debug.assert(math.isNegativeInf(-infinite_f128)); |
|||
try expect(math.isInf(infinite_value)); |
|||
try expect(math.isPositiveInf(infinite_value)); |
|||
try expect(!math.isNegativeInf(infinite_value)); |
|||
try expect(!math.isFinite(infinite_value)); |
|||
// isFinite(f128) is not implemented. |
|||
} |
|||
//debug.assert(!math.isFinite(infinite_f128)); |
|||
}</ |
}</syntaxhighlight> |
||
{{out}} |
|||
<pre> |
|||
$ zig test src/infinity_float.zig |
|||
All 1 tests passed. |
|||
</pre> |
|||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
zkl doesn't like INF, NaN, etc but sorta knows about them: |
zkl doesn't like INF, NaN, etc but sorta knows about them: |
||
<lang |
<syntaxhighlight lang="zkl">1.5/0</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,590: | Line 1,699: | ||
=={{header|ZX Spectrum Basic}}== |
=={{header|ZX Spectrum Basic}}== |
||
ZX Spectrum BASIC has no infinity handling; <lang |
ZX Spectrum BASIC has no infinity handling; <syntaxhighlight lang="zxbasic">PRINT 1/0</syntaxhighlight> will be met with <pre>6 Number too big, 0:1</pre> |
||
A quick doubling loop will get you halfway to the maximum floating point value: |
A quick doubling loop will get you halfway to the maximum floating point value: |
||
< |
<syntaxhighlight lang="zxbasic">10 LET z=1 |
||
20 PRINT z |
20 PRINT z |
||
30 LET z=z*2 |
30 LET z=z*2 |
||
40 GO TO 20</ |
40 GO TO 20</syntaxhighlight> |
||
Output will end with: |
Output will end with: |
||
Line 1,606: | Line 1,715: | ||
Precision has been lost by this stage through the loop, but one more manual double and subtract 1 will get you the true displayable maximum of 1.7014118E+38 (or 2^127-1). |
Precision has been lost by this stage through the loop, but one more manual double and subtract 1 will get you the true displayable maximum of 1.7014118E+38 (or 2^127-1). |
||
{{omit from|6502 Assembly|Has no dedicated floating point hardware}} |
|||
{{omit from|8080 Assembly|Has no dedicated floating point hardware}} |
|||
{{omit from|bc|No infinity. Numbers have unlimited precision, so no largest possible value.}} |
{{omit from|bc|No infinity. Numbers have unlimited precision, so no largest possible value.}} |
||
{{omit from|Brainf***}} |
{{omit from|Brainf***}} |
||
{{omit from|Computer/zero Assembly|Has no dedicated floating point hardware}} |
|||
{{omit from|dc|No infinity. Numbers have unlimited precision, so no largest possible value.}} |
{{omit from|dc|No infinity. Numbers have unlimited precision, so no largest possible value.}} |
||
{{omit from|Integer BASIC}} |
{{omit from|Integer BASIC}} |
||
Line 1,614: | Line 1,726: | ||
{{omit from|VBScript}} |
{{omit from|VBScript}} |
||
{{omit from|UNIX Shell}} |
{{omit from|UNIX Shell}} |
||
{{omit from|Z80 Assembly|Has no dedicated floating point hardware}} |
|||
[[Category:Irrational numbers]] |
[[Category:Irrational numbers]] |
Latest revision as of 08:24, 23 July 2024
You are encouraged to solve this task according to the task description, using any language you may know.
- Task
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.5 as floating point type.
- Related task
11l
print(Float.infinity)
- Output:
inf
ActionScript
ActionScript has the built in function isFinite() to test if a number is finite or not.
trace(5 / 0); // outputs "Infinity"
trace(isFinite(5 / 0)); // outputs "false"
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;
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:
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;
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:
subtype Safe_Float is Float range Float'Range;
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.
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))
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: *
APL
For built-in functions, reduction over an empty list returns the identity value for that function.
E.g., +/⍬
gives 0
, and ×/⍬
gives 1.
The identity value for ⌊
(minimum) is the largest possible value. For APL implementations
that support infinity, this will be infinity. Otherwise, it will be some large, but finite value.
inf ← {⌊/⍬}
- Output:
∞
1.797693135E308
Argile
(simplified)
use std
printf "%f\n" atof "infinity" (: this prints "inf" :)
#extern :atof<text>: -> real
Arturo
print infinity
print neg infinity
- Output:
∞ -∞
AWK
BEGIN {
k=1;
while (2^(k-1) < 2^k) k++;
INF = 2^k;
print INF;
}
This has been tested with GAWK 3.1.7 and MAWK, both return
inf
BASIC
BASIC256
onerror TratoError
infinity = 1e300*1e300
end
TratoError:
if lasterror = 29 then print lasterrormessage
return
BBC BASIC
*FLOAT 64
PRINT FNinfinity
END
DEF FNinfinity
LOCAL supported%, maxpos, prev, inct
supported% = TRUE
ON ERROR LOCAL supported% = FALSE
IF supported% THEN = 1/0
RESTORE ERROR
inct = 1E10
REPEAT
prev = maxpos
inct *= 2
ON ERROR LOCAL inct /= 2
maxpos += inct
RESTORE ERROR
UNTIL maxpos = prev
= maxpos
Output:
1.79769313E308
bootBASIC
There are no floating point numbers in bootBASIC. All numbers and variables are 2 byte unsigned integers.
The code below can't print anything on the screen, plus the program won't end. No way is currently known to break out of the program.
10 print 1/0
BQN
Positive infinity is just ∞:
∞ + 1 ∞ ∞ - 3 ∞ -∞ ¯∞ ∞ - ∞ NaN
C
A previous solution used atof("infinity"), which returned infinity with some C libraries but returned zero with MinGW.
C89 has a macro HUGE_VAL in <math.h>. HUGE_VAL is a double. HUGE_VAL will be infinity if infinity exists, else it will be the largest possible number. HUGE_VAL is a double.
#include <math.h> /* HUGE_VAL */
#include <stdio.h> /* printf() */
double inf(void) {
return HUGE_VAL;
}
int main() {
printf("%g\n", inf());
return 0;
}
The output from the above program might be "inf", "1.#INF", or something else.
C99 also has a macro for infinity:
#define _ISOC99_SOURCE
#include <math.h>
#include <stdio.h>
int main() {
printf("%g\n", INFINITY);
return 0;
}
C#
using System;
class Program
{
static double PositiveInfinity()
{
return double.PositiveInfinity;
}
static void Main()
{
Console.WriteLine(PositiveInfinity());
}
}
Output:
Infinity
C++
#include <limits>
double inf()
{
if (std::numeric_limits<double>::has_infinity)
return std::numeric_limits<double>::infinity();
else
return std::numeric_limits<double>::max();
}
Clojure
Java's floating-point types (float, double) all support infinity. Clojure has literals for infinity:
##Inf ;; same as Double/POSITIVE_INFINITY
##-Inf ;; same as Double/NEGATIVE_INFINITY
(Double/isInfinite ##Inf) ;; true
The largest possible number in Java (without using the Big classes) is also in the Double class (def biggestNumber Double/MAX_VALUE). Its value is (1+(1-2^(-52)))*2^1023 or 1.7976931348623157*10^308 (a.k.a. "big"). Other number classes (Integer, Long, Float, Byte, and Short) have maximum values that can be accessed in the same way.
CoffeeScript
CoffeeScript compiles to JavaScript, and as such it inherits the properties of JavaScript.
JavaScript has a special global property called "Infinity":
Infinity
as well as constants in the Number class:
Number.POSITIVE_INFINITY
Number.NEGATIVE_INFINITY
The global isFinite function tests for finiteness:
isFinite x
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.
5.1.2, Intel, OS X, 32-bit
> (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
Component Pascal
BlackBox Component Builder
MODULE Infinity;
IMPORT StdLog;
PROCEDURE Do*;
VAR
x: REAL;
BEGIN
x := 1 / 0;
StdLog.String("x:> ");StdLog.Real(x);StdLog.Ln
END Do;
Execute: ^Q Infinity.Do
Output:
x:> inf
D
auto inf() {
return typeof(1.5).infinity;
}
void main() {}
Delphi
Delphi defines the following constants in Math:
Infinity = 1.0 / 0.0;
NegInfinity = -1.0 / 0.0;
Test for infinite value using:
Math.IsInfinite()
Dyalect
Dyalect floating point number support positive infinity:
func infinityTask() => Float.Infinity
E
def infinityTask() {
return Infinity # predefined variable holding positive infinity
}
EasyLang
print number "inf"
# or
print 1 / 0
Eiffel
class
APPLICATION
inherit
ARGUMENTS
create
make
feature {NONE} -- Initialization
number:REAL_64
make
-- Run application.
do
number := 2^2000
print(number)
print("%N")
print(number.is_positive_infinity)
print("%N")
end
end
Output:
Infinity True
Erlang
No infinity available. Largest floating point number is supposed to be 1.80e308 (IEEE 754-1985 double precision 64 bits) but that did not work. However 1.79e308 is fine, so max float is somewhere close to 1.80e308.
ERRE
Every type has its "infinity" constant: MAXINT for 16-bit integer, MAXREAL for single precision floating and MAXLONGREAL for double precision floating. An infinity test can be achieved with an EXCEPTION:
PROGRAM INFINITY
EXCEPTION
PRINT("INFINITY")
ESCI%=TRUE
END EXCEPTION
BEGIN
ESCI%=FALSE
K=1
WHILE 2^K>0 DO
EXIT IF ESCI%
K+=1
END WHILE
END PROGRAM
Euphoria
constant infinity = 1E400
? infinity -- outputs "inf"
F#
printfn "%f" (1.0/0.0)
- Output:
Infinity
Factor
1/0.
Fantom
Fantom's Float
data type is an IEEE 754 64-bit floating point type. Positive infinity is represented by the constant posInf
.
class Main
{
static Float getInfinity () { Float.posInf }
public static Void main () { echo (getInfinity ()) }
}
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)
FreeBASIC
' FB 1.05.0 Win64
#Include "crt/math.bi"
#Print Typeof(1.5) ' Prints DOUBLE at compile time
Dim d As Typeof(1.5) = INFINITY
Print d; " (String representation of Positive Infinity)"
Sleep
- Output:
1.#INF (String representation of Positive Infinity)
FutureBasic
FB has a native definition for infinite floating point types. As demonstrated below, it returns "inf".
printf @"%g", INFINITY
HandleEvents
- Output:
inf
Fōrmulæ
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation —i.e. XML, JSON— they are intended for storage and transfer purposes more than visualization and edition.
Programs in Fōrmulæ are created/edited online in its website.
In this page you can see and run the program(s) related to this task and their results. You can also change either the programs or the parameters they are called with, for experimentation, but remember that these programs were created with the main purpose of showing a clear solution of the task, and they generally lack any kind of validation.
Solution
Fōrmulæ does not use floating point numbers, but arbitrary-size integers and arbitrary-precision decimal numbers.
Infinity is a predefined expression in Fōrmulæ.
Reduction of certain expressions can produce it:
GAP
# Floating point infinity
inf := FLOAT_INT(1) / FLOAT_INT(0);
IS_FLOAT(inf);
#true;
# GAP has also a formal ''infinity'' value
infinity in Cyclotomics;
# true
Go
package main
import (
"fmt"
"math"
)
// function called for by task
func posInf() float64 {
return math.Inf(1) // argument specifies positive infinity
}
func main() {
x := 1.5 // type of x determined by literal
// that this compiles demonstrates that PosInf returns same type as x,
// the type specified by the task.
x = posInf() // test function
fmt.Println(x, math.IsInf(x, 1)) // demonstrate result
}
Output:
+Inf true
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.
def biggest = { Double.POSITIVE_INFINITY }
Test program:
println biggest()
printf ( "0x%xL \n", Double.doubleToLongBits(biggest()) )
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:
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
Icon and Unicon
Icon and Unicon have no infinity value (or defined maximum or minimum values). Reals are implemented as C doubles and the behavior could vary somewhat from platform to platform. Both explicitly check for divide by zero and treat it as a runtime error (201), so it's not clear how you could produce one with the possible exception of externally called code.
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
Io
inf := 1/0
or
Number constants inf
IS-BASIC
PRINT INF
Output:
9.999999999E62
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:
_ * 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
_
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:
double infinity = Double.POSITIVE_INFINITY; //defined as 1.0/0.0
Double.isInfinite(infinity); //true
As a function:
public static double getInf(){
return Double.POSITIVE_INFINITY;
}
The largest possible number in Java (without using the Big classes) is also in the Double class.
double biggestNumber = Double.MAX_VALUE;
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":
Infinity
as well as constants in the Number class:
Number.POSITIVE_INFINITY
Number.NEGATIVE_INFINITY
The global isFinite() function tests for finiteness:
isFinite(x)
Joy
1 1024 ldexp dup neg stack.
- Output:
[-inf inf]
jq
Sufficiently recent versions of the C, Go and Rust implementations of jq (jq, gojq, and jaq, respectively) all allow `infinite` as a scalar value in jq programs; jq and gojq display its value as 1.7976931348623157e+308. The C implementation also allows the token `inf` when reading JSON, and stores it as `infinite`.
The C implementation of jq uses IEEE 754 64-bit floating-point arithmetic, and very large real number literals, e.g. 1e1000, are evaluated as IEEE 754 infinity, so if your version of jq does not include `infinite` as a built-in, you could therefore define it as follows:
def infinite: 1e1000;
To test whether a jq value is equal to `infinite` or `- infinite`, one can use the built-in filter `isinfinite`. One can also use `==` in the expected manner.
Julia
Julia uses IEEE floating-point arithmetic and includes a built-in constant `Inf` for (64-bit) floating-point infinity. Inf32 can be used as 32-bit infinity, when avoiding type promotions to Int64.
julia> julia> Inf32 == Inf64 == Inf16 == Inf
true
K
K has predefined positive and negative integer and float infinities: -0I, 0I, -0i, 0i. They have following properties:
/ Integer infinities
/ 0I is just 2147483647
/ -0I is just -2147483647
/ -2147483648 is a special "null integer"(NaN) 0N
0I*0I
1
0I-0I
0
0I+1
0N
0I+2
-0I
0I+3 / -0I+1
-2147483646
0I-1
2147483646
0I%0I
1
0I^2
4.611686e+18
0I^0I
0i
0I^-0I
0.0
1%0
0I
0%0
0
0i^2
0i
0i^0i
0i
/ Floating point infinities in K are something like
/ IEEE 754 values
/ Also there is floating point NaN -- 0n
0i+1
0i
0i*0i
0i
0i-0i
0n
0i%0i
0n
0i%0n
0n
/ but
0.0%0.0
0.0
Klingphix
1e300 dup mult tostr "inf" equal ["Infinity" print] if
" " input
Kotlin
fun main(args: Array<String>) {
val p = Double.POSITIVE_INFINITY // +∞
println(p.isInfinite()) // true
println(p.isFinite()) // false
println("${p < 0} ${p > 0}") // false true
val n = Double.NEGATIVE_INFINITY // -∞
println(n.isInfinite()) // true
println(n.isFinite()) // false
println("${n < 0} ${n > 0}") // true false
}
- Output:
true false false true true false true false
Lambdatalk
Lambdatalk is built on Javascript and can inherit lots of its capabilities. For instance:
{/ 1 0}
-> Infinity
{/ 1 Infinity}
-> 0
{< {pow 10 100} Infinity}
-> true
{< {pow 10 1000} Infinity}
-> false
Lasso
Lasso supports 64-bit decimals.. This gives Lasso's decimal numbers a range from approximately negative to positive 2x10^300 and with precision down to 2x10^-300. Lasso also supports decimal literals for NaN (not a number) as well and positive and negative infinity.
infinity
'<br />'
infinity -> type
-> inf
decimal
Lingo
Lingo stores floats using IEEE 754 double-precision (64-bit) format. INF is not a constant that can be used programmatically, but only a special return value.
x = (1-power(2, -53)) * power(2, 1023) * 2
put ilk(x), x
-- #float 1.79769313486232e308
x = (1-power(2, -53)) * power(2, 1023) * 3
put ilk(x), x, -x
-- #float INF -INF
Lua
function infinity()
return 1/0 --lua uses unboxed C floats for all numbers
end
M2000 Interpreter
Rem : locale 1033
Module CheckIt {
Form 66,40
Cls 5
Pen 14
\\ Ensure True/False for Print boolean (else -1/0)
\\ from m2000 console use statement Switches without Set.
\\ use Monitor statement to see all switches.
Set Switches "+SBL"
IF version<9.4 then exit
IF version=9.4 and revision<25 then exit
Function Infinity(positive=True) {
buffer clear inf as byte*8
m=0x7F
if not positive then m+=128
return inf, 7:=m, 6:=0xF0
=eval(inf, 0 as double)
}
K=Infinity(false)
L=Infinity()
Function TestNegativeInfinity(k) {
=str$(k, 1033) = "-1.#INF"
}
Function TestPositiveInfinity(k) {
=str$(k, 1033) = "1.#INF"
}
Function TestInvalid {
=str$(Number, 1033) = "-1.#IND"
}
Pen 11 {Print " True True"}
Print TestNegativeInfinity(K), TestPositiveInfinity(L)
Pen 11 {Print " -1.#INF 1.#INF -1.#INF 1.#INF -1.#INF 1.#INF"}
Print K, L, K*100, L*100, K+K, L+L
M=K/L
Pen 11 {Print " -1.#IND -1.#IND True True" }
Print K/L, L/K, TestInvalid(M), TestInvalid(K/L)
M=K+L
Pen 11 {Print " -1.#IND -1.#IND -1.#IND True True"}
Print M, K+L, L+K, TestInvalid(M), TestInvalid(K+L)
Pen 11 {Print " -1.#INF 1.#INF"}
Print 1+K+2, 1+L+2
Pen 11 {Print " -1.#INF"}
Print K-L
Pen 11 {Print " 1.#INF"}
Print L-K
}
Checkit
Maple
Maple's floating point numerics are a strict extension of IEEE/754 and IEEE/854 so there is already a built-in infinity. (In fact, there are several.) The following procedure just returns the floating point (positive) infinity directly.
> proc() Float(infinity) end();
Float(infinity)
There is also an exact infinity ("infinity"), a negative float infinity ("Float(-infinity)" or "-Float(infinity)") and a suite of complex infinities. The next procedure returns a boxed machine (double precision) float infinity.
> proc() HFloat(infinity) end();
HFloat(infinity)
Mathematica / Wolfram Language
Mathematica has infinity built-in as a symbol. Which can be used throughout the software:
Sum[1/n^2,{n,Infinity}]
1/Infinity
Integrate[Exp[-x^2], {x, -Infinity, Infinity}]
10^100 < Infinity
gives back:
Pi^2/6 0 Sqrt[Pi] True
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]]:
Integrate[Exp[-x^2]/(x^2 - 1), {x, 0, DirectedInfinity[Exp[I Pi/4]]}]
gives back:
-((Pi (I+Erfi[1]))/(2 E))
MATLAB / Octave
MATLAB implements the IEEE 754 floating point standard as the default for all numeric data types. +Inf and -Inf are by default implemented and supported by MATLAB. To check if a variable has the value +/-Inf, one can use the built-in function "isinf()" which will return a Boolean 1 if the number is +/-inf.
a = +Inf;
isinf(a)
Returns:
ans = 1
Maxima
/* Maxima has inf (positive infinity) and minf (negative infinity) */
declare(x, real)$
is(x < inf);
/* true */
is(x > minf);
/* true */
/* However, it is an error to try to divide by zero, even with floating-point numbers */
1.0/0.0;
/* expt: undefined: 0 to a negative exponent.
-- an error. To debug this try: debugmode(true); */
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
infinity := 4095.99998;
MiniScript
MiniScript uses IEEE numerics, so:
posInfinity = 1/0
print posInfinity
- Output:
INF
Modula-2
MODULE inf;
IMPORT InOut;
BEGIN
InOut.WriteReal (1.0 / 0.0, 12, 12);
InOut.WriteLn
END inf.
Producing
jan@Beryllium:~/modula/rosetta$ inf
**** RUNTIME ERROR bound check error
Floating point exception
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
Nemerle
Both single and double precision floating point numbers support PositiveInfinity, NegativeInfinity and NaN.
def posinf = double.PositiveInfinity;
def a = IsInfinity(posinf); // a = true
def b = IsNegativeInfinity(posinf); // b = false
def c = IsPositiveInfinity(posinf); // c = true
Nim
Inf
is a predefined constant in Nim:
var f = Inf
echo f
NS-HUBASIC
10 PRINT 1/0
- Output:
?DZ ERROR is a division by zero error in NS-HUBASIC.
?DZ ERROR IN 10
OCaml
infinity
is already a pre-defined value in OCaml.
# infinity;; - : float = infinity # 1.0 /. 0.0;; - : float = infinity
Oforth
10 1000.0 powf dup println dup neg println 1 swap / println
- Output:
1.#INF -1.#INF 0
Ol
Inexact numbers support can be disabled during recompilation using "-DOLVM_INEXACTS=0" command line argument. Inexact numbers in Ol demands the existence of infinity, by demanding IEEE numbers. There are two signed infinity numbers (as constants) in Ol:
+inf.0 ; positive infinity -inf.0 ; negative infinity
(define (infinite? x) (or (equal? x +inf.0) (equal? x -inf.0)))
(infinite? +inf.0) ==> #true
(infinite? -inf.0) ==> #true
(infinite? +nan.0) ==> #false
(infinite? 123456) ==> #false
(infinite? 1/3456) ==> #false
(infinite? 17+28i) ==> #false
OpenEdge/Progress
The unknown value (represented by a question mark) can be considered to equal infinity. There is no difference between positive and negative infinity but the unknown value sometimes sorts low and sometimes sorts high when used in queries.
MESSAGE
1.0 / 0.0 SKIP
-1.0 / 0.0 SKIP(1)
( 1.0 / 0.0 ) = ( -1.0 / 0.0 )
VIEW-AS ALERT-BOX.
Output
--------------------------- Message (Press HELP to view stack trace) --------------------------- ? ? yes --------------------------- OK Help ---------------------------
OxygenBasic
Using double precision floats:
print 1.5e-400 '0
print 1.5e400 '#INF
print -1.5e400 '#-INF
print 0/-1.5 '-0
print 1.5/0 '#INF
print -1.5/0 '#-INF
print 0/0 '#qNAN
function f() as double
return -1.5/0
end function
print f '#-INF
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
PARI/GP
+oo
infty()={
[1] \\ Used for many functions like intnum
};
Pascal
See Delphi
PascalABC.NET
##
Write(real.PositiveInfinity);
- Output:
Infinity
Perl
Positive infinity:
my $x = 0 + "inf";
my $y = 0 + "+inf";
Negative infinity:
my $x = 0 - "inf";
my $y = 0 + "-inf";
The "0 +
..." is used here to make sure that the variable stores a value that is actually an infinitive number instead of just a string "inf"
but in practice one can use just:
my $x = "inf";
and $x
while originally holding a string will get converted to an infinite number when it is first used as a number.
Some programmers use expressions that overflow the IEEE floating point numbers such as:
my $x = 1e1000;
which is 101000 or googol10 or even numbers like this one:
my $y = 10**10**10;
which is 1010000000000 but it has to make some assumptions about the underlying hardware format and its size. Furthermore, using such literals in the scope of some pragmas such as bigint
, bignum
or bigrat
would actually compute those numbers:
use bigint;
my $x = 1e1000;
my $y = 10**10**10; # N.B. this will consume vast quantities of RAM
Here the $x
and $y
when printed would give 1001 and 10000000001-digit numbers respectively, the latter taking no less than 10GB of space to just output.
Under those pragmas, however, there is a simpler way to use infinite values, thanks to the inf
symbol being exported into the namespace by default:
use bigint;
my $x = inf;
my $y = -inf;
Phix
with javascript_semantics constant infinity = 1e300*1e300 ? infinity
- Output:
desktop/Phix:
inf
pwa/p2js:
Infinity
Phixmonti
1e300 dup * tostr "inf" == if "Infinity" print endif
PHP
This is how you get infinity:
INF
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.
PicoLisp
The symbol 'T' is used to represent infinite values, e.g. for the length of circular lists, and is greater than any other value in comparisons. PicoLisp has only very limited floating point support (scaled bignum arithmetics), but some functions return 'T' for infinite results.
(load "@lib/math.l")
: (exp 1000.0)
-> T
PL/I
declare x float, y float (15), z float (18);
put skip list (huge(x), huge(y), huge(z));
PostScript
/infinity { 9 99 exp } def
PowerShell
A .NET floating-point number representing infinity is available.
function infinity {
[double]::PositiveInfinity
}
PureBasic
PureBasic uses IEEE 754 coding for float types. PureBasic also includes the function Infinity() that return the positive value for infinity and the boolean function IsInfinite(value.f) that returns true if the floating point value is either positive or negative infinity.
If OpenConsole()
Define.d a, b
b = 0
;positive infinity
PrintN(StrD(Infinity())) ;returns the value for positive infinity from builtin function
a = 1.0
PrintN(StrD(a / b)) ;calculation results in the value of positive infinity
;negative infinity
PrintN(StrD(-Infinity())) ;returns the value for negative infinity from builtin function
a = -1.0
PrintN(StrD(a / b)) ;calculation results in the value of negative infinity
Print(#crlf$ + #crlf$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf
Outputs
+Infinity +Infinity -Infinity -Infinity
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
If float('infinity') doesn't work on your platform, you could use this trick:
>>> 1e999 1.#INF
It works by trying to create a float bigger than the machine can handle.
QB64
#include<math.h>
//save as inf.h
double inf(void){
return HUGE_VAL;
}
Declare CustomType Library "inf"
Function inf#
End Declare
Print inf
QBasic
DECLARE FUNCTION f! ()
ON ERROR GOTO TratoError
PRINT 0!
PRINT 0 / -1.5
PRINT 1.5 / 0
PRINT 0 / 0
PRINT f
END
TratoError:
PRINT "Error "; ERR; " on line "; ERL; CHR$(9); " --> ";
SELECT CASE ERR
CASE 6
PRINT "Overflow"
RESUME NEXT
CASE 11
PRINT "Division by zero"
RESUME NEXT
CASE ELSE
PRINT "Unexpected error, ending program."
END
END SELECT
FUNCTION f!
f! = -1.5 / 0
END FUNCTION
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
# 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.000000e+00 -1.000000e+00 0.000000e+00 1.797693e+308
# [5] -1.797693e+308 1.797693e+308 -1.797693e+308
Racket
as in Scheme:
#lang racket
+inf.0 ; positive infinity
(define (finite? x) (< -inf.0 x +inf.0))
(define (infinite? x) (not (finite? x)))
Raku
(formerly Perl 6) Inf support is required by language spec on all abstract Numeric types (in the absence of subset constraints) including Num, Rat and Int types. Native integers cannot support Inf, so attempting to assign Inf will result in an exception; native floats are expected to follow IEEE standards including +/- Inf and NaN.
my $x = 1.5/0; # Failure: catchable error, if evaluated will return: "Attempt to divide by zero ...
my $y = (1.5/0).Num; # assigns 'Inf'
REXX
The language specifications for REXX are rather open-ended when it comes to language limits.
Limits on numbers are expressed as: The REXX interpreter has to at least handle exponents up to nine (decimal) digits.
So it's up to the writers of the REXX interpreter to decide what limits are to be implemented or enforced.
For the default setting of NUMERIC DIGITS 9 the biggest number that can be used is (for the Regina REXX and R4 REXX interpreters): .999999999e+999999999
For a setting of NUMERIC DIGITS 100 the biggest number that can be used is: (for the Regina REXX interpreter) .9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999e+999999999 (for the R4 REXX interpreter) .9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999e+9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999 ... and so on with larger NUMERIC DIGITS
For most REXX interpreters, the maximum number of digits is only limited by virtual storage,
but the pratical limit would be a little less than half of available virtual storage,
which would (realistically) be around one billion digits. Other interpreters have a limitation of roughly 8 million digits.
RLaB
>> x = inf()
inf
>> isinf(x)
1
>> inf() > 10
1
>> -inf() > 10
0
RPL
- Input:
MAXR →NUM
- Output:
1: 1.7976931348E+308
Ruby
Infinity is a Float value
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
a = Float::INFINITY # => Infinity
Rust
Rust has builtin function for floating types which returns infinity. This program outputs 'inf'.
fn main() {
let inf = f32::INFINITY;
println!("{}", inf);
}
Scala
See also
In order to be compliant with IEEE-754, Scala has all support for infinity on its floating-point types (float, double). You can get infinity from constants in the corresponding wrapper class; for example, Double:
val inf = Double.PositiveInfinity //defined as 1.0/0.0
inf.isInfinite; //true
The largest possible number in Scala (without using the Big classes) is also in the Double class.
val biggestNumber = Double.MaxValue
REPL session:
scala> 1 / 0.
res2: Double = Infinity
scala> -1 / 0.
res3: Double = -Infinity
scala> 1 / Double.PositiveInfinity
res4: Double = 0.0
scala> 1 / Double.NegativeInfinity
res5: Double = -0.0
Scheme
+inf.0 ; positive infinity
(define (finite? x) (< -inf.0 x +inf.0))
(define (infinite? x) (not (finite? x)))
Seed7
Seed7s floating-point type (float) supports infinity. The library float.s7i defines the constant Infinity as:
const float: Infinity is 1.0 / 0.0;
Checks for infinity can be done by comparing with this constant.
Sidef
var a = 1.5/0 # Inf
say a.is_inf # true
say a.is_pos # true
var b = -1.5/0 # -Inf
say b.is_ninf # true
say b.is_neg # true
var inf = Inf
var ninf = -Inf
say (inf == -ninf) # true
Slate
PositiveInfinity
Smalltalk
Each of the finite-precision Float classes (FloatE, FloatD, FloatQ), have an "infinity" method that returns infinity in that type.
st> FloatD infinity Inf st> 1.0 / 0.0 Inf
The behavior is slightly different, in that an exception is raised if you divide by zero:
FloatD infinity -> INF
1.0 / 0.0 -> "ZeroDivide exception"
but we can simulate the other behavior with:
[
1.0 / 0.0
] on: ZeroDivide do:[:ex |
ex proceedWith: (FloatD infinity)
]
-> INF
Standard ML
Real.posInf
- Real.posInf; val it = inf : real - 1.0 / 0.0; val it = inf : real
Swift
Swift's floating-point types (Float, Double, and any other type that conforms to the FloatingPointNumber protocol) all support infinity. You can get infinity from the infinity class property in the type:
let inf = Double.infinity
inf.isInfinite //true
As a function:
func getInf() -> Double {
return Double.infinity
}
Tcl
Tcl 8.5 has Infinite as a floating point value, not an integer value
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
A maximal integer is not easy to find, as Tcl switches to unbounded integers when a 64-bit integer is about to roll over:
% 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
A theoretical MAXINT, though very impractical, could be
string repeat 9 [expr 2**32-1]
TI-89 BASIC
∞
TorqueScript
function infinity()
{
return 1/0;
}
Trith
The following functions are included as part of the core operators:
: inf 1.0 0.0 / ;
: -inf inf neg ;
: inf? abs inf = ;
Ursa
Infinity is a defined value in Ursa.
decl double d
set d Infinity
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.
#import flo
infinity = inf!
Visual Basic
Positive infinity, negative infinity and indefinite number (usable as NaN) can be generated by deliberately dividing by zero under the influence of On Error Resume Next
:
Option Explicit
Private Declare Sub GetMem8 Lib "msvbvm60.dll" _
(ByVal SrcAddr As Long, ByVal TarAddr As Long)
Sub Main()
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
Debug.Print "PlusInfinity = " & CStr(PlusInfinity) _
& " (" & DoubleAsHex(PlusInfinity) & ")"
Debug.Print "MinusInfinity = " & CStr(MinusInfinity) _
& " (" & DoubleAsHex(MinusInfinity) & ")"
Debug.Print "IndefiniteNumber = " & CStr(IndefiniteNumber) _
& " (" & DoubleAsHex(IndefiniteNumber) & ")"
End Sub
Function DoubleAsHex(ByVal d As Double) As String
Dim l(0 To 1) As Long
GetMem8 VarPtr(d), VarPtr(l(0))
DoubleAsHex = Right$(String$(8, "0") & Hex$(l(1)), 8) _
& Right$(String$(8, "0") & Hex$(l(0)), 8)
End Function
- Output:
PlusInfinity = 1,#INF (7FF0000000000000)MinusInfinity = -1,#INF (FFF0000000000000) IndefiniteNumber = -1,#IND (FFF8000000000000)
V (Vlang)
import math
fn main() {
mut x := 1.5 // type of x determined by literal
// that this compiles demonstrates that PosInf returns same type as x,
// the type specified by the task.
x = math.inf(1)
println('$x ${math.is_inf(x, 1)}') // demonstrate result
}
Wren
Wren certainly supports infinity for floating point numbers as we already have a method Num.isInfinity to test for it.
var x = 1.5
var y = x / 0
System.print("x = %(x)")
System.print("y = %(y)")
System.print("'x' is infinite? %(x.isInfinity)")
System.print("'y' is infinite? %(y.isInfinity)")
- Output:
x = 1.5 y = infinity 'x' is infinite? false 'y' is infinite? true
XPL0
The IEEE 754 floating point standard is used.
int A;
real X;
[Format(0, 15); \output in scientific notation
A:= addr X; \get address of (pointer to) X
A(0):= $FFFF_FFFF; \stuff in largest possible value
A(1):= $7FEF_FFFF;
RlOut(0, X); \display it
]
- Output:
1.797693134862320E+308
Yabasic
infinity = 1e300*1e300
if str$(infinity) = "inf" print "Infinity"
Zig
Works with: 0.10.x, 0.11.x, 0.12.0-dev.1577+9ad03b628
Assumes that defaul float optimization mode was not changed via @setFloatMode (performed in Strict mode, not Optimized, latter is equivalent to -ffast-math).
const std = @import("std");
const math = std.math;
test "infinity" {
const expect = std.testing.expect;
const float_types = [_]type{ f16, f32, f64, f80, f128, c_longdouble };
inline for (float_types) |T| {
const infinite_value: T = comptime std.math.inf(T);
try expect(math.isInf(infinite_value));
try expect(math.isPositiveInf(infinite_value));
try expect(!math.isNegativeInf(infinite_value));
try expect(!math.isFinite(infinite_value));
}
}
- Output:
$ zig test src/infinity_float.zig All 1 tests passed.
zkl
zkl doesn't like INF, NaN, etc but sorta knows about them:
1.5/0
- Output:
Exception thrown: MathError(INF (number is infinite))
ZX Spectrum Basic
ZX Spectrum BASIC has no infinity handling;
PRINT 1/0
will be met with
6 Number too big, 0:1
A quick doubling loop will get you halfway to the maximum floating point value:
10 LET z=1
20 PRINT z
30 LET z=z*2
40 GO TO 20
Output will end with:
4.2535296E+37 8.5070592E+37 6 Number too big, 30:1
Precision has been lost by this stage through the loop, but one more manual double and subtract 1 will get you the true displayable maximum of 1.7014118E+38 (or 2^127-1).
- Programming Tasks
- Basic language learning
- Discrete math
- 11l
- ActionScript
- Ada
- ALGOL 68
- APL
- Argile
- Arturo
- AWK
- BASIC
- BASIC256
- BBC BASIC
- BootBASIC
- BQN
- C
- C sharp
- C++
- Clojure
- CoffeeScript
- Common Lisp
- Component Pascal
- D
- Delphi
- Dyalect
- E
- EasyLang
- Eiffel
- Erlang
- ERRE
- Euphoria
- F Sharp
- Factor
- Fantom
- Forth
- Fortran
- FreeBASIC
- FutureBasic
- Fōrmulæ
- GAP
- Go
- Groovy
- Haskell
- Icon
- Unicon
- IDL
- Io
- IS-BASIC
- J
- Java
- JavaScript
- Joy
- Jq
- Julia
- K
- Klingphix
- Kotlin
- Lambdatalk
- Lasso
- Lingo
- Lua
- M2000 Interpreter
- Maple
- Mathematica
- Wolfram Language
- MATLAB
- Octave
- Maxima
- Metafont
- MiniScript
- Modula-2
- Modula-3
- Nemerle
- Nim
- NS-HUBASIC
- OCaml
- Oforth
- Ol
- OpenEdge/Progress
- OxygenBasic
- Oz
- PARI/GP
- Pascal
- PascalABC.NET
- Perl
- Phix
- Phixmonti
- PHP
- PicoLisp
- PL/I
- PostScript
- PowerShell
- PureBasic
- Python
- QB64
- QBasic
- R
- Racket
- Raku
- REXX
- RLaB
- RPL
- Ruby
- Rust
- Scala
- Scheme
- Seed7
- Sidef
- Slate
- Smalltalk
- Standard ML
- Swift
- Tcl
- TI-89 BASIC
- TorqueScript
- Trith
- Ursa
- Ursala
- Visual Basic
- V (Vlang)
- Wren
- XPL0
- Yabasic
- Zig
- Zkl
- ZX Spectrum Basic
- 6502 Assembly/Omit
- 8080 Assembly/Omit
- Bc/Omit
- Brainf***/Omit
- Computer/zero Assembly/Omit
- Dc/Omit
- Integer BASIC/Omit
- Retro/Omit
- Sed/Omit
- VBScript/Omit
- UNIX Shell/Omit
- Z80 Assembly/Omit
- Irrational numbers
- Pages with too many expensive parser function calls