prime_factorize(1) -> ? (Pythonic error signalling) - python

I have a prime_factorize function that returns a dictionary mapping from prime divisors to their powers. E.g., 50 = 2^1 * 5^2, so prime_factorize(50) returns {2 : 1, 5 : 2}.
Assuming this is the documented behavior, what would be the least surprising way to signal an error if called 0, 1, or a negative number? Throw ValueError? Return something that looks like correct output (e.g., prime_factorize(-5) -> {-1: 1, 5: 1})? return an empty dict?
And if you have a better format for returning a prime factorization, I'd love to hear that too.

In prime_factorize(n):
if n < 2 or not isinstance(n, numbers.Integral):
raise ValueError("Number to factor can't be less than 2")
else:
# normal behavior
That way users a.) get meaningful info about what went wrong and b.) can handle the exception in a try...except block.
I definitely wouldn't turn incorrect data or an empty dict, because that will lead to some tricky debugging the first time someone passes an improper value. Raise exceptions, that's what they're there for!

Not sure why you're using a dictionary here. Wouldn't a list of 2-tuples work as well? I.e., have prime_factor(50) return [(2,1), ((5,2)].
Use of a dictionary presupposes that you know the key and want to look up it's value, which doesn't seem to be the case for the prime factors of an arbitrary number.

More to do with the concept of prime factorization than anything to do with python; factorization should raise an exception for all x < 2 or non integer.

Math functions in the standard library may be a good reference to take as the least surprising behaviour. Let's check math.sqrt for example: it returns a ValueError on domain error (here n < 1) and a TypeError on unexpected type (here if you send a non-integer). So I'd write.
if is not isinstance(n, numbers.Integral):
raise TypeError("an integer is required")
elif n < 1:
raise ValueError("number to factor can't be less than 1")
...
And I agree with Piotr Findeisen, a factorization of 1 as an empty dictionary seems perfectly sound.

Related

Does python operator not need condition statement?

I saw the code snippet that I think it is illegal, but not sure yet.
This is not exactly the same code, but I try to keep the original as much as I can.
def validate_check(string):
try:
len(string) > 0
# do something
except Error:
# do something
Doesn't len(string) > 0 have to be in condition statement? Or is it something python syntax?
Doesn't len(string) > 0 have to be in condition statement?
No, but the example you've provided doesn't make a ton of sense.
Here's a different, similar construction that might help:
x = input()
try:
10 / int(x)
except ZeroDivisionError:
print("Can't divide by zero")
except ValueError:
print("Can't convert to int")
The result of 10 / int(x) is calculated (to see whether it will raise an error), but the result of that calculation is thrown away.
The reason I say your example is a bit weird is because the comparison with zero will have no effect whatsoever. So while the code will serve as a way of testing whether len can be called on string, that's about all it'll do.
This is valid syntax. But if you write:
len(string) > 0
print("hi")
then "hi" will be printed regardless of the length of the string. The only relevance this statement has is that it will throw an exception when either string has no length, or the result of len(string) is not comparable to 0.
What the author of the code is doing is avoiding the more complicated check if isinstance(string, str) and string: (or, I guess, if isinstance(string, collections.abc.Sized) and len(string) > 0).
If string is None, the len function will raise an error.
Perhaps it's the reason why your function is named validate_check.

Why am I receiving a "no ordering relation defined for complex numbers" error?

See this question for some background. My main problem on that question was solved, and it was suggested that I ask another one for a second problem I'm having:
print cubic(1, 2, 3, 4) # Correct solution: about -1.65
...
if x > 0:
TypeError: no ordering relation is defined for complex numbers
print cubic(1, -3, -3, -1) # Correct solution: about 3.8473
if x > 0:
TypeError: no ordering relation is defined for complex numbers
Cubic equations with one real root and two complex roots are receiving an error, even though I am using the cmath module and have defined the cube root function to handle complex numbers. Why is this?
Python's error messages are pretty good, as these things go: unlike some languages I could mention, they don't feel like random collections of letters. So when Python complains of the comparison
if x > 0:
that
TypeError: no ordering relation is defined for complex numbers
you should take it at its word: you're trying to compare a complex number x to see whether or not it's greater than zero, and Python doesn't know how to order complex numbers. Is 2j > 0? Is -2j > 0? Etc. In the face of ambiguity, refuse the temptation to guess.
Now, in your particular case, you've already branched on whether or not x.imag != 0, so you know that x.imag == 0 when you're testing x and you can simply take the real part, IIUC:
>>> x = 3+0j
>>> type(x)
<type 'complex'>
>>> x > 0
Traceback (most recent call last):
File "<ipython-input-9-36cf1355a74b>", line 1, in <module>
x > 0
TypeError: no ordering relation is defined for complex numbers
>>> x.real > 0
True
It is not clear from your example code what x is, but it seems it must be a complex number. Sometimes, when using complex numerical methods, an approximate solution will come up as a complex number even though the exact solution is supposed to be real.
Complex numbers have no natural ordering, so an inequality x > 0 makes no sense if x is complex. That's what the type error is about.

Checking whether a variable is an integer or not [duplicate]

This question already has answers here:
What's the canonical way to check for type in Python?
(15 answers)
Closed 3 years ago.
The community reviewed whether to reopen this question last year and left it closed:
Original close reason(s) were not resolved
How do I check whether a variable is an integer?
If you need to do this, do
isinstance(<var>, int)
unless you are in Python 2.x in which case you want
isinstance(<var>, (int, long))
Do not use type. It is almost never the right answer in Python, since it blocks all the flexibility of polymorphism. For instance, if you subclass int, your new class should register as an int, which type will not do:
class Spam(int): pass
x = Spam(0)
type(x) == int # False
isinstance(x, int) # True
This adheres to Python's strong polymorphism: you should allow any object that behaves like an int, instead of mandating that it be one.
BUT
The classical Python mentality, though, is that it's easier to ask forgiveness than permission. In other words, don't check whether x is an integer; assume that it is and catch the exception results if it isn't:
try:
x += 1
except TypeError:
...
This mentality is slowly being overtaken by the use of abstract base classes, which let you register exactly what properties your object should have (adding? multiplying? doubling?) by making it inherit from a specially-constructed class. That would be the best solution, since it will permit exactly those objects with the necessary and sufficient attributes, but you will have to read the docs on how to use it.
All proposed answers so far seem to miss the fact that a double (floats in python are actually doubles) can also be an integer (if it has nothing after the decimal point). I use the built-in is_integer() method on doubles to check this.
Example (to do something every xth time in a for loop):
for index in range(y):
# do something
if (index/x.).is_integer():
# do something special
Edit:
You can always convert to a float before calling this method. The three possibilities:
>>> float(5).is_integer()
True
>>> float(5.1).is_integer()
False
>>> float(5.0).is_integer()
True
Otherwise, you could check if it is an int first like Agostino said:
def is_int(val):
if type(val) == int:
return True
else:
if val.is_integer():
return True
else:
return False
Here's a summary of the different methods mentioned here:
int(x) == x
try x = operator.index(x)
isinstance(x, int)
isinstance(x, numbers.Integral)
and here's how they apply to a variety of numerical types that have integer value:
You can see they aren't 100% consistent. Fraction and Rational are conceptually the same, but one supplies a .index() method and the other doesn't. Complex types don't like to convert to int even if the real part is integral and imaginary part is 0.
(np.int8|16|32|64(5) means that np.int8(5), np.int32(5), etc. all behave identically)
If you really need to check then it's better to use abstract base classes rather than concrete classes. For an integer that would mean:
>>> import numbers
>>> isinstance(3, numbers.Integral)
True
This doesn't restrict the check to just int, or just int and long, but also allows other user-defined types that behave as integers to work.
>>> isinstance(3, int)
True
See here for more.
Note that this does not help if you're looking for int-like attributes. In this case you may also want to check for long:
>>> isinstance(3L, (long, int))
True
I've seen checks of this kind against an array/index type in the Python source, but I don't think that's visible outside of C.
Token SO reply: Are you sure you should be checking its type? Either don't pass a type you can't handle, or don't try to outsmart your potential code reusers, they may have a good reason not to pass an int to your function.
Why not try something like:
if x%1 == 0:
Rather than over complicate things, why not just a simple
if type(var) is int:
A simple method I use in all my software is this. It checks whether the variable is made up of numbers.
test = input("Enter some text here: ")
if test.isdigit() == True:
print("This is a number.")
else:
print("This is not a number.")
You can also use str.isdigit. Try looking up help(str.isdigit)
def is_digit(str):
return str.isdigit()
Found a related question here on SO itself.
Python developers prefer to not check types but do a type specific operation and catch a TypeError exception. But if you don't know the type then you have the following.
>>> i = 12345
>>> type(i)
<type 'int'>
>>> type(i) is int
True
it's really astounding to see such a heated discussion coming up when such a basic, valid and, i believe, mundane question is being asked.
some people have pointed out that type-checking against int (and long) might loose cases where a big decimal number is encountered. quite right.
some people have pointed out that you should 'just do x + 1 and see whether that fails. well, for one thing, this works on floats too, and, on the other hand, it's easy to construct a class that is definitely not very numeric, yet defines the + operator in some way.
i am at odds with many posts vigorously declaring that you should not check for types. well, GvR once said something to the effect that in pure theory, that may be right, but in practice, isinstance often serves a useful purpose (that's a while ago, don't have the link; you can read what GvR says about related issues in posts like this one).
what is funny is how many people seem to assume that the OP's intent was to check whether the type of a given x is a numerical integer type—what i understood is what i normally mean when using the OP's words: whether x represents an integer number. and this can be very important: like ask someone how many items they'd want to pick, you may want to check you get a non-negative integer number back. use cases like this abound.
it's also, in my opinion, important to see that (1) type checking is but ONE—and often quite coarse—measure of program correctness, because (2) it is often bounded values that make sense, and out-of-bounds values that make nonsense. sometimes just some intermittent values make sense—like considering all numbers, only those real (non-complex), integer numbers might be possible in a given case.
funny non-one seems to mention checking for x == math.floor( x ). if that should give an error with some big decimal class, well, then maybe it's time to re-think OOP paradigms. there is also PEP 357 that considers how to use not-so-obviously-int-but-certainly-integer-like values to be used as list indices. not sure whether i like the solution.
If you want to check that a string consists of only digits, but converting to an int won't help, you can always just use regex.
import re
x = "01234"
match = re.search("^\d+$", x)
try: x = match.group(0)
except AttributeError: print("not a valid number")
Result: x == "01234"
In this case, if x were "hello", converting it to a numeric type would throw a ValueError, but data would also be lost in the process. Using a regex and catching an AttributeError would allow you to confirm numeric characters in a string with, for instance, leading 0's.
If you didn't want it to throw an AttributeError, but instead just wanted to look for more specific problems, you could vary the regex and just check the match:
import re
x = "h01234"
match = re.search("\D", x)
if not match:
print("x is a number")
else:
print("encountered a problem at character:", match.group(0))
Result: "encountered a problem at character: h"
That actually shows you where the problem occurred without the use of exceptions. Again, this is not for testing the type, but rather the characters themselves. This gives you much more flexibility than simply checking for types, especially when converting between types can lose important string data, like leading 0's.
why not just check if the value you want to check is equal to itself cast as an integer as shown below?
def isInt(val):
return val == int(val)
It is very simple to check in python. You can do like this:
Suppose you want to check a variable is integer or not!
## For checking a variable is integer or not in python
if type(variable) is int:
print("This line will be executed")
else:
print("Not an integer")
If you are reading from a file and you have an array or dictionary with values of multiple datatypes, the following will be useful.
Just check whether the variable can be type casted to int(or any other datatype you want to enforce) or not.
try :
int(a);
#Variable a is int
except ValueError :
# Variable a is not an int
In the presence of numpy check like ..
isinstance(var, numbers.Integral)
.. (slow) or ..
isinstance(var, (int, long, np.integer))
.. in order to match all type variants like np.int8, np.uint16, ...
(Drop long in PY3)
Recognizing ANY integer-like object from anywhere is a tricky guessing game. Checking
var & 0 == 0
for truth and non-exception may be a good bet. Similarly, checking for signed integer type exclusively:
var ^ -1 == -var - 1
If the variable is entered like a string (e.g. '2010'):
if variable and variable.isdigit():
return variable #or whatever you want to do with it.
else:
return "Error" #or whatever you want to do with it.
Before using this I worked it out with try/except and checking for (int(variable)), but it was longer code. I wonder if there's any difference in use of resources or speed.
A simple way to do this is to directly check if the remainder on division by 1 is 0 or not.
if this_variable % 1 == 0:
list.append(this_variable)
else:
print 'Not an Integer!'
Here is a simple example how you can determine an integer
def is_int(x):
print round(x),
if x == round(x):
print 'True',
else:
print 'False'
is_int(7.0) # True
is_int(7.5) # False
is_int(-1) # True
If you just need the value, operator.index (__index__ special method) is the way to go in my opinion. Since it should work for all types that can be safely cast to an integer. I.e. floats fail, integers, even fancy integer classes that do not implement the Integral abstract class work by duck typing.
operator.index is what is used for list indexing, etc. And in my opinion it should be used for much more/promoted.
In fact I would argue it is the only correct way to get integer values if you want to be certain that floating points, due to truncating problems, etc. are rejected and it works with all integral types (i.e. numpy, etc.) even if they may not (yet) support the abstract class.
This is what __index__ was introduced for!
If you want to check with no regard for Python version (2.x vs 3.x), use six (PyPI) and it's integer_types attribute:
import six
if isinstance(obj, six.integer_types):
print('obj is an integer!')
Within six (a very light-weight single-file module), it's simply doing this:
import sys
PY3 = sys.version_info[0] == 3
if PY3:
integer_types = int,
else:
integer_types = (int, long)
use the int function to help
intchecker = float(input('Please enter a integer: '))
intcheck = 0
while intcheck != 1:
if intchecker - int(intchecker) > 0:
intchecker = float(input("You didn't enter a integer. "
"Please enter a integer: "))
else:
intcheck = 1
print('you have entered a integer')
I was writing a program to check if a number was square and I encountered this issue, the
code I used was:
import math
print ("this program will tell you if a number is square")
print ("enter an integer")
num = float(input())
if num > 0:
print ("ok!")
num = (math.sqrt(num))
inter = int(num)
if num == inter:
print ("It's a square number, and its root is")
print (num)
else:
print ("It's not a square number, but its root is")
print (num)
else:
print ("That's not a positive number!")
To tell if the number was an integer I converted the float number you get from square rooting the user input to a rounded integer (stored as the value ), if those two numbers were equal then the first number must have been an integer, allowing the program to respond. This may not be the shortest way of doing this but it worked for me.
You can do this.
if type(x) is int:
#!/usr/bin/env python
import re
def is_int(x):
if(isinstance(x,(int,long))):
return True
matchObj = re.match(r'^-?\d+\.(\d+)',str(x))
if matchObj:
x = matchObj.group(1)
if int(x)-0==0:
return True
return False
print is_int(6)
print is_int(1.0)
print is_int(1.1)
print is_int(0.1)
print is_int(-956.0)
If you have not int you can do just this:
var = 15.4
if(var - int(var) != 0):
print "Value is not integer"
If you want to write a Python 2-3 compatible code
To test whether a value is an integer (of any kind), you can to do this :
# Python 2 and 3:
import sys
if sys.version_info < (3,):
integer_types = (int, long,)
else:
integer_types = (int,)
>>> isinstance(1, integer_types)
True
# Python 2 only:
if isinstance(x, (int, long)):
...
# Python 3 only:
if isinstance(x, int):
...
source : http://python3porting.com/differences.html
A more general approach that will attempt to check for both integers and integers given as strings will be
def isInt(anyNumberOrString):
try:
int(anyNumberOrString) #to check float and int use "float(anyNumberOrString)"
return True
except ValueError :
return False
isInt("A") #False
isInt("5") #True
isInt(8) #True
isInt("5.88") #False *see comment above on how to make this True
you can do this by:
name = 'Bob'
if type(name) == str:
print 'this works'
else:
print 'this does not work'
and it will return 'this works'... but if you change name to int(1) then it will return 'this does not work' because it is now a string...
you can also try:
name = int(5)
if type(name) == int:
print 'this works'
else:
print 'this does not work'
and the same thing will happen
There is another option to do the type check.
For example:
n = 14
if type(n)==int:
return "this is an int"

an error in taking an input in python

111111111111111111111111111111111111111111111111111111111111
when i take this as input , it appends an L at the end like this
111111111111111111111111111111111111111111111111111111111111L
thus affecting my calculations on it .. how can i remove it?
import math
t=raw_input()
l1=[]
a=0
while (str(t)!="" and int(t)!= 0):
l=1
k=int(t)
while(k!= 1):
l=l+1
a=(0.5 + 2.5*(k %2))*k + k % 2
k=a
l1.append(l)
t=raw_input()
a=a+1
for i in range(0,int(a)):
print l1[i]
this is my code and it works for every test case except 111111111111111111111111111111111111111111111111111111111111
so i guess something is wrong when python considers such a huge number
It looks like there are two distinct things happening here. First, as the other posters have noted, the L suffix simply indicates that Python has converted the input value to a long integer. The second issue is on this line:
a=(0.5 + 2.5*(k %2))*k + k % 2
This implicitly results in a floating point number for the value of (0.5 + 2.5*(k %2))*k. Since floats only have 53 bits of precision the result is incorrect due to rounding. Try refactoring the line to avoid floating point math, like this:
a=(1 + 5*(k %2))*k//2 + k % 2
It's being input as a Long Integer, which should behave just like any other number in terms of doing calculations. It's only when you display it using repr (or something that invokes repr, like printing a list) that it gets the 'L'.
What exactly is going wrong?
Edit: Thanks for the code. As far as I can see, giving it a long or short number makes no difference, but it's not really clear what it's supposed to do.
As RichieHindle noticed in his answer, it is being represented as a Long Integer. You can read about the different ways that numbers can be represented in Python at the following page.
When I use numbers that large in Python, I see the L at the end of the number as well. It shouldn't affect any of the computations done on the number. For example:
>>> a = 111111111111111111111111111111111111111
>>> a + 1
111111111111111111111111111111111111112L
>>> str(a)
'111111111111111111111111111111111111111'
>>> int(a)
111111111111111111111111111111111111111L
I did that on the python command line. When you output the number, it will have the internal representation for the number, but it shouldn't affect any of your computations. The link I reference above specifies that long integers have unlimited precision. So cool!
Another way to avoid numerical errors in python is to use Decimal type instead of standard float.
Please refer to official docs
Are you sure that L is really part of it? When you print such large numbers, Python will append an L to indicate it's a long integer object.

In what contexts do programming languages make real use of an Infinity value?

So in Ruby there is a trick to specify infinity:
1.0/0
=> Infinity
I believe in Python you can do something like this
float('inf')
These are just examples though, I'm sure most languages have infinity in some capacity. When would you actually use this construct in the real world? Why would using it in a range be better than just using a boolean expression? For instance
(0..1.0/0).include?(number) == (number >= 0) # True for all values of number
=> true
To summarize, what I'm looking for is a real world reason to use Infinity.
EDIT: I'm looking for real world code. It's all well and good to say this is when you "could" use it, when have people actually used it.
Dijkstra's Algorithm typically assigns infinity as the initial edge weights in a graph. This doesn't have to be "infinity", just some arbitrarily constant but in java I typically use Double.Infinity. I assume ruby could be used similarly.
Off the top of the head, it can be useful as an initial value when searching for a minimum value.
For example:
min = float('inf')
for x in somelist:
if x<min:
min=x
Which I prefer to setting min initially to the first value of somelist
Of course, in Python, you should just use the min() built-in function in most cases.
There seems to be an implied "Why does this functionality even exist?" in your question. And the reason is that Ruby and Python are just giving access to the full range of values that one can specify in floating point form as specified by IEEE.
This page seems to describe it well:
http://steve.hollasch.net/cgindex/coding/ieeefloat.html
As a result, you can also have NaN (Not-a-number) values and -0.0, while you may not immediately have real-world uses for those either.
In some physics calculations you can normalize irregularities (ie, infinite numbers) of the same order with each other, canceling them both and allowing a approximate result to come through.
When you deal with limits, calculations like (infinity / infinity) -> approaching a finite a number could be achieved. It's useful for the language to have the ability to overwrite the regular divide-by-zero error.
Use Infinity and -Infinity when implementing a mathematical algorithm calls for it.
In Ruby, Infinity and -Infinity have nice comparative properties so that -Infinity < x < Infinity for any real number x. For example, Math.log(0) returns -Infinity, extending to 0 the property that x > y implies that Math.log(x) > Math.log(y). Also, Infinity * x is Infinity if x > 0, -Infinity if x < 0, and 'NaN' (not a number; that is, undefined) if x is 0.
For example, I use the following bit of code in part of the calculation of some log likelihood ratios. I explicitly reference -Infinity to define a value even if k is 0 or n AND x is 0 or 1.
Infinity = 1.0/0.0
def Similarity.log_l(k, n, x)
unless x == 0 or x == 1
k * Math.log(x.to_f) + (n-k) * Math.log(1.0-x)
end
-Infinity
end
end
Alpha-beta pruning
I use it to specify the mass and inertia of a static object in physics simulations. Static objects are essentially unaffected by gravity and other simulation forces.
In Ruby infinity can be used to implement lazy lists. Say i want N numbers starting at 200 which get successively larger by 100 units each time:
Inf = 1.0 / 0.0
(200..Inf).step(100).take(N)
More info here: http://banisterfiend.wordpress.com/2009/10/02/wtf-infinite-ranges-in-ruby/
I've used it for cases where you want to define ranges of preferences / allowed.
For example in 37signals apps you have like a limit to project number
Infinity = 1 / 0.0
FREE = 0..1
BASIC = 0..5
PREMIUM = 0..Infinity
then you can do checks like
if PREMIUM.include? current_user.projects.count
# do something
end
I used it for representing camera focus distance and to my surprise in Python:
>>> float("inf") is float("inf")
False
>>> float("inf") == float("inf")
True
I wonder why is that.
I've used it in the minimax algorithm. When I'm generating new moves, if the min player wins on that node then the value of the node is -∞. Conversely, if the max player wins then the value of that node is +∞.
Also, if you're generating nodes/game states and then trying out several heuristics you can set all the node values to -∞/+∞ which ever makes sense and then when you're running a heuristic its easy to set the node value:
node_val = -∞
node_val = max(heuristic1(node), node_val)
node_val = max(heuristic2(node), node_val)
node_val = max(heuristic2(node), node_val)
I've used it in a DSL similar to Rails' has_one and has_many:
has 0..1 :author
has 0..INFINITY :tags
This makes it easy to express concepts like Kleene star and plus in your DSL.
I use it when I have a Range object where one or both ends need to be open
I've used symbolic values for positive and negative infinity in dealing with range comparisons to eliminate corner cases that would otherwise require special handling:
Given two ranges A=[a,b) and C=[c,d) do they intersect, is one greater than the other, or does one contain the other?
A > C iff a >= d
A < C iff b <= c
etc...
If you have values for positive and negative infinity that respectively compare greater than and less than all other values, you don't need to do any special handling for open-ended ranges. Since floats and doubles already implement these values, you might as well use them instead of trying to find the largest/smallest values on your platform. With integers, it's more difficult to use "infinity" since it's not supported by hardware.
I ran across this because I'm looking for an "infinite" value to set for a maximum, if a given value doesn't exist, in an attempt to create a binary tree. (Because I'm selecting based on a range of values, and not just a single value, I quickly realized that even a hash won't work in my situation.)
Since I expect all numbers involved to be positive, the minimum is easy: 0. Since I don't know what to expect for a maximum, though, I would like the upper bound to be Infinity of some sort. This way, I won't have to figure out what "maximum" I should compare things to.
Since this is a project I'm working on at work, it's technically a "Real world problem". It may be kindof rare, but like a lot of abstractions, it's convenient when you need it!
Also, to those who say that this (and other examples) are contrived, I would point out that all abstractions are somewhat contrived; that doesn't mean they are useful when you contrive them.
When working in a problem domain where trig is used (especially tangent) infinity is an answer that can come up. Trig ends up being used heavily in graphics applications, games, and geospatial applications, plus the obvious math applications.
I'm sure there are other ways to do this, but you could use Infinity to check for reasonable inputs in a String-to-Float conversion. In Java, at least, the Float.isNaN() static method will return false for numbers with infinite magnitude, indicating they are valid numbers, even though your program might want to classify them as invalid. Checking against the Float.POSITIVE_INFINITY and Float.NEGATIVE_INFINITY constants solves that problem. For example:
// Some sample values to test our code with
String stringValues[] = {
"-999999999999999999999999999999999999999999999",
"12345",
"999999999999999999999999999999999999999999999"
};
// Loop through each string representation
for (String stringValue : stringValues) {
// Convert the string representation to a Float representation
Float floatValue = Float.parseFloat(stringValue);
System.out.println("String representation: " + stringValue);
System.out.println("Result of isNaN: " + floatValue.isNaN());
// Check the result for positive infinity, negative infinity, and
// "normal" float numbers (within the defined range for Float values).
if (floatValue == Float.POSITIVE_INFINITY) {
System.out.println("That number is too big.");
} else if (floatValue == Float.NEGATIVE_INFINITY) {
System.out.println("That number is too small.");
} else {
System.out.println("That number is jussssst right.");
}
}
Sample Output:
String representation: -999999999999999999999999999999999999999999999
Result of isNaN: false
That number is too small.
String representation: 12345
Result of isNaN: false
That number is jussssst right.
String representation: 999999999999999999999999999999999999999999999
Result of isNaN: false
That number is too big.
It is used quite extensively in graphics. For example, any pixel in a 3D image that is not part of an actual object is marked as infinitely far away. So that it can later be replaced with a background image.
I'm using a network library where you can specify the maximum number of reconnection attempts. Since I want mine to reconnect forever:
my_connection = ConnectionLibrary(max_connection_attempts = float('inf'))
In my opinion, it's more clear than the typical "set to -1 to retry forever" style, since it's literally saying "retry until the number of connection attempts is greater than infinity".
Some programmers use Infinity or NaNs to show a variable has never been initialized or assigned in the program.
If you want the largest number from an input but they might use very large negatives. If I enter -13543124321.431 it still works out as the largest number since it's bigger than -inf.
enter code here
initial_value = float('-inf')
while True:
try:
x = input('gimmee a number or type the word, stop ')
except KeyboardInterrupt:
print("we done - by yo command")
break
if x == "stop":
print("we done")
break
try:
x = float(x)
except ValueError:
print('not a number')
continue
if x > initial_value: initial_value = x
print("The largest number is: " + str(initial_value))
You can to use:
import decimal
decimal.Decimal("Infinity")
or:
from decimal import *
Decimal("Infinity")
For sorting
I've seen it used as a sort value, to say "always sort these items to the bottom".
To specify a non-existent maximum
If you're dealing with numbers, nil represents an unknown quantity, and should be preferred to 0 for that case. Similarly, Infinity represents an unbounded quantity, and should be preferred to (arbitrarily_large_number) in that case.
I think it can make the code cleaner. For example, I'm using Float::INFINITY in a Ruby gem for exactly that: the user can specify a maximum string length for a message, or they can specify :all. In that case, I represent the maximum length as Float::INFINITY, so that later when I check "is this message longer than the maximum length?" the answer will always be false, without needing a special case.

Categories