Alternative methods of initializing floats to '+inf', '-inf' and 'nan'

To initialize float constants to +inf, -inf, nan I always use float() called with a string:

print(float('inf'), float('+inf'), float('-inf'), float('nan'))

This prints:

[inf, inf, -inf, nan]

1.) Does there exist in Python an alternative method of initializing these constants (not calling float with a string)?

2.) Can I produce these constants (+/-inf, nan) with some mathematical operation?

E.g. for setting the variable f to +inf, by writing something like f = 1.0 / 0.0 (obviously, this is a division by zero error).

Technically, yes, there are other ways of initializing such values, but they're all either less obvious, or much less convenient.

If your platform uses IEEE floating point,1 any float arithmetic that overflows, without raising any other flags besides overflow, is guaranteed to give you inf. This means 1.0 / 0.0 probably won't work (Python will detect that this is a division by zero), but the even simpler 1e500 will.2

Once you have inf, you can just do -inf and inf/inf to get the negative infinity and NaN values.

But would someone reading your code understand 1e500 / 1e500 as readily as float('nan')? Probably not.

Meanwhile, you can always do something like struct.unpack('>f', b'\x7f\x80\0\0')[0], which unpacks the well-defined bit pattern for an IEEE big-endian double inf value as a float, whether your float is that type under the covers or not. But why would you want to write (or read) that?3


But, if you're using Python 3.5 or later, you don't need to initialize those values; you can just use the constants in the math module:

print(math.inf, +math.inf, -math.inf, math.nan)

And if you're using Python 2.7 or 3.4 or something, you can always just define your own constants and use them over and over:

inf, nan = float('inf'), float('nan')

print(inf, +inf, -inf, nan)

1. Technically, Python doesn't require IEEE floating point. In fact, what it requires are something that acts like the platform's C double—which C doesn't require to be an IEEE type, and only if that makes sense for the implementation (e.g., Jython is obviously going to use the relevant Java type without caring what the C compiler used to compile the JVM thinks), and it doesn't clarify exactly what it means to act like a C double. However, the float type—not to mention things like the math module—really isn't going to work unless float is something reasonably close to an IEEE float type, like maybe the pre-IEEE IBM and Intel types or the not-quite-IEEE Motorola compat types. Also, as of 2018, the only supported platforms by any of the three existing Python 3.x implementations all give you either IEEE 754-1985 double or IEEE 754-2008 float64. But, if this is really a potential issue for your code, you should check sys.float_info to verify whatever assumptions are relevant.

2. It's conceivable that some platform might use an IEEE 754-1985 long double or an IEEE 754-2008 float128 or something. If you're worried about that, just use a bigger number. Or, say, 1e500 ** 1e500 ** 1e500.

3. Well, if you specifically need a quiet or signaling NaN, or one with a custom bit pattern instead of the default one… but anyone who needs that presumably already knows they need that.

Variable Declaration, Initialization, and Data Types, To cast (or typecast) a variable's value explicitly to another type, precede the variable's name with the other type's name in parentheses: int height = 2; float fheight  Technically, yes, there are other ways of initializing such values, but they're all either less obvious, or much less convenient. If your platform uses IEEE floating point, 1 any float arithmetic that overflows, without raising any other flags besides overflow, is guaranteed to give you inf.

You can access those mathematical constants from the math module:

>>> from math import inf, nan
>>> inf
inf
>>> nan
nan
>>> inf == float('inf')
True

Behind the scenes, in the CPython inplementation, math.inf and math.nan are generated using the same technique as that which float('inf') and float('nan') use; both approaches invoke the API functions _Py_dg_infinity and _Py_dg_stdnan respectively.

Java.Lang.Float class in Java, Float(String s): Creates a Float object initialized with the parsed float value provided by string In all other cases compareTo method should be preferred. Alternatives to Floating display: inline-block. One of the popular uses for floats is in creating layouts. Position: Absolute. Another scenario in which floats are used is when we want to align sibling elements on A Case For Floating. Although these alternatives can cover most cases,

Not sure if this is what you want, but numpy has variables built in for that.

import numpy as np

a = np.inf
b = -np.inf
c = np.nan

print(a, b, c)
[inf, -inf, nan]

How to initialize float variable in c to some other variables, 8/100=0.08 and as it returns integer that means that it stores only zero . that is again assigned to a float variable so it shows you 0.0 as your output . if you want​  Print value of float[] 10.1 20.2 30.3 Print value of Float[] 10.1 20.2 null. How to Initialize int or Integer array in declaration? How to Initialize long or Long array in declaration? How to Initialize double or Double array in declaration? How to Initialize boolean or Boolean array in declaration? Newer Post Home Older Post.

math.inf constant was introduced in python3.5, you can read more about in https://docs.python.org/3/library/math.html#constants:

math.inf A floating-point positive infinity. (For negative infinity, use -math.inf.) Equivalent to the output of float('inf').

New in version 3.5.

As you can see below, they're both identical ones:

>>> import math
>>> math.inf == float('inf')
True
>>> math.isinf(math.inf)
True
>>>

In case you're also interested about how infinity is checked under the curtains you can take a look to the Py_IS_INFINITY macro.

1.2 Variables | C++ Basics, Literals of other types can be written by adding a suffix from the following When a float is initialized from a double variable or constant (not a  Andrej Kesely. DevOps. 9 Alternative methods of initializing floats to '+inf', '-inf' and 'nan' Aug 1 '18. 9 Most pythonic callable generating True? Dec 1 '19.

If you are looking to get these values through mathematical operations:

import numpy as np
a = np.array([-1,0,1],dtype='int8')
a/0

Output:

array([-inf,  nan,  inf])

This result is consistent with the IEEE 754 floating point behavior.

In IEEE 754 arithmetic, a ÷ +0 is positive infinity when a is positive, negative infinity when a is negative, and NaN when a = ±0.

C++ Primer Plus, However, this approach can be a safe one for initializing a character array to a float balances[100] {}; Third, as discussed in Chapter 3, list-initialization Later, this chapter discusses an alternative method based on a string class library. Floating-point literals are considered doubles unless you specify that they're just floats. (Similarly, integer literals are ints unless specified otherwise.) Append the letter f to the number to make it a float: float density = 20.0f; The JLS has comprehensive typing rules for literal values.

Float (Java Platform SE 7 ), In addition, this class provides several methods for converting a float to a String and a String to a float , as well as other constants and methods useful when Returns a new float initialized to the value represented by the specified String , as​  Well, even if you are a float master there are certain things that they just can’t do. For instance: The elusive “centered float”, which is oft-times desirable, requires additional markup and multiple CSS properties to achieve. With the display method this is simply done by applyingtext-align: center to the wrapper.

Variables and Data Types, There are two major categories of data types in the Java language: primitive Double-precision floating point (other types) char 16-bit Unicode character A Local variables and member variables can be initialized when they are declared. is assigning approxTen to a float, or possibly an int depending on the types of variables in the equation. Since approxTen is a float, you can't append something to it because floats don't have append or extend methods. Going further back in your code, your code to initialize a list of floats is not doing what you think: approxTen=['f']

Variables -- declaring and assigning values, Java provides types to represent several kinds of number, e.g. integer and floating point, non-numerical things like text, and other more abstract things. Today one of the primary ways that we have replaced our table-dependent ways is the use of floats for layout. By default, sequential HTML elements will appear vertically stacked. Floats serve as a way for us to line elements up horizontally. Float a list of li elements to the left and you’ve got yourself a nice little horizontal navigation menu.

Comments
  • Just define inf = float("inf") etc. and use those names.
  • How do I type a floating point infinity literal in python - Stack Overflow -
  • The math module seems ok. And for the second part? Can I produce these constants with some mathematical operation?
  • @AndrejKesely You can — e.g., 1e500 is inf, and 1e500 / 1e500 is nan on most platforms—but I don't think you should.
  • @AndrejKesely Updated the answer to get into the gory details a bit more.
  • I see, it's quite a rabbit hole ;) But your answer is exhausting for my case, thank you.
  • @AndrejKesely Yeah, Python has always been a bit loosely specified around the edges, so questions like this usually involve a rabbit hole, where you get to choose how far you want to go, rather than, say, in Java, where you can just quote from the 1800-page spec. Ultimately, we're just guessing at how future implementors might interpret future versions of the spec based on the hidden assumptions elsewhere in the reference or the past behavior on platforms like 68000 Mac and Amiga or pre-S/390 IBM…