How to use infinity in python - python

I am working with graphs in python. I am trying to get the distance between each vertex. I need to use the value INFINITY (represented using the string "-") for a situation in which there is no direct path between one vertex and another. I tried a couple of solutions. One was using a crazy large int to represent infinity. However, I researched and found that this is poor practice. I also saw several solutions on stack overflow that made use of the math module's infinity function. However, this is not appropriate for my problem, as my INFINITY value is being used in a UI and must look graphically pleasing. This is why my INFINITY must remain as the string "-". This is the error I am getting with my current line of code:
TypeError: '<' not supported between instances of 'str' and 'int'
I am not completely sure, but I think the < is coming from my use of the min() function.
This error is coming from the following code:
for i in range(length):
for j in range(length):
for k in range(length):
#print('40:', int(temp[j][i]), int(temp[i][k]))
temp[j][k] = min(temp[j][k], addWithInfinity(temp[j][i],temp[i][k]))
Temp just refers to a matrix which I received as an argument in the method I am currently working with. Here is my addWithInfinity method:
def addWithInfinity(a, b):
"""If a == INFINITY or b == INFINITY, returns INFINITY.
Otherwise, returns a + b."""
if a == LinkedDirectedGraph.INFINITY or b == LinkedDirectedGraph.INFINITY:
return LinkedDirectedGraph.INFINITY
else: return a + b
My issue is that I am trying to compare infinity with an int. I tried to convert INFINITY to an int like this: int(INFINITY) ( or int('-') ) but I got the following error:
ValueError: invalid literal for int() with base 10: '-'
Any ideas how I can get away with the comparison between an int and INFINITY (which is a string)?

Use float("inf") or math.inf
See also How can I represent an infinite number in Python?
>>> float("inf") > 5
True
>>> float("inf") < 10**100
False
>>> import math
>>> float("inf") == math.inf
True
If you need to use some other value than "inf" for infinity, such as '-' in your example, you could try/except it, either
checking if the initial value is your target string (if a == '-':)
parsing the error calling float on it (if "'-'" in str(err_string):)
try:
a = float(a)
except ValueError as ex:
# special-case for ValueError: could not convert string to float: '-'
if "'-'" in str(ex).split(":")[-1]:
a = float("inf")
else: # re-raise other ValueErrors
raise ex

String "-" is not infinity even you mean it. In Python, you can obtain the type in two ways:
float("inf")
or
import math
math.inf
Your problem is not related to the usage or use cases of infinity type, but it is the representation issue. I believe you should use the normal infinity type in your math and create a property in your class that returns "-" and then use it only when you need to represent it on UI but not in your math.
The issue that you have is more about the decoupling of representation and logic.

Related

Is there a prefab python function out there that turns only integer floats into ints?

I would like to turn float integers (123.0) into ints (123).
What I would like the function to do:
Input: 2.1
Output: Exception, cannot turn float into int
Input: 2.0
Output: 2
Using int() on a float seems to just be math.floor() and that is not what I'm looking for.
You can check if after you use int() it the same value as the float
def convert(num):
if num == int(num):
return int(num)
raise Exception('Cannot turn float into int')
As a side note, using int() is not exactly as using math.floor(), try with negative numbers. What is the difference between int() and floor() in Python 3?
I don't know of a built-in that does it directly, but it is easy to create your own function. You can use .is_integer() on the input-value to check if the float is directly castable to int:
def strict_int(value):
if value.is_integer():
return int(value)
raise ValueError("cannot turn uneven float into int")
print(strict_int(3.0))
print(strict_int(3.1))
Output:
3
...
ValueError: cannot turn uneven float into int
But be warned, that there may be some unexpected behavior resulting from the way floats are represented. Try this for example:
print(strict_int(0.3 + 0.3 + 0.3 + 0.1))
This "1.0" will fail when trying to strictly convert to an int as it is in fact 0.9999999999999999! If you use the standard int it will work in that it gives you a result, but the result for int(0.3 + 0.3 + 0.3 + 0.1) is 0, probably not what you'd expect. But this is a general issue with how floats are represented and not directly related to the used methods. So you'll encounter this anywhere floats are present.
Here is an interesting post that goes a bit more into detail about the potential issues.
I guess i would just do
def convert(n):
return int(f"{n:g}")

How to compare Scalar to Float

I am trying to compare the value I get from np.max(err) and np.min(err) to a float number, and I can't for the life of me figure out how to do it.
I've tried converting them to float by using the float() function, but that got me:
IndexError: invalid index to scalar variable.
Code:
err = [evaluation[i] - Ytest_set[i] for i in range(len(evaluation))]
if (0-float(np.min(err)))<0.05 & (0-float(np.max(err)))<0.05:
self.eval_pass = True
the goal is so for np.min(err) to be recognized as a float so that it can be compared to 0.05.
This much simpler code should be OK:
if -np.min(err)<0.05 and -np.max(err)<0.05:
self.eval_pass = True
If not, than you probably have a problem with the definition of err
BTW: as err is a list, you don't have to use np.min()\np.max(), and use the plain min()\min() instead.

Smallest Number in Python

PROBLEM STATEMENT: Write a Python script to determine the smallest positive double number in Python.
Your code should produce a variable called smallest_num which is the smallest double number in Python.
Your script should determine this value in a systematic manner. You may NOT simply call a built-in function that returns this value or access a built-in variable that contains this information. This includes np.finfo() and other built-in functions or variables.
The setup code gives the following variables:
Your code snippet should define the following variables:
Name Type Description
smallest_num floating point The smallest number possible in Python
Attempted Solution
import numpy as np
import math
def machineEpsilon(func=float):
machine_epsilon = func(1)
while func(1)+func(machine_epsilon) != func(1):
machine_epsilon_last = machine_epsilon
machine_epsilon = func(machine_epsilon) / func(2)
return machine_epsilon_last
sum_f = machineEpsilon(np.float64)
smallest_sum = float(sum_f)
print(isinstance(smallest_sum, float))
print(smallest_sum)
Output
True
2.220446049250313e-16
However, I am unable to get the correct answer. As the true smallest number is much smaller than the printed value. I know this number will be underflow to zero and I might want to do some comparison here. But i am a bit stuck. Any thoughts?
Probably the most reasonable thing to do would be to directly compute the next double-precision float after 0.0:
smallest_num = np.nextafter(0, 1)
This does not simply call a built-in function that returns the smallest positive double-precision float, or access a variable pre-set to that value. However, people get weird when they see function call syntax in problems like this, so it risks being marked incorrect anyway.
Taking advantage of how IEEE754 floating-point representation and rounding works, we can start with 1.0 and divide by 2 until the next division would underflow:
smallest_num = 1.0
while smallest_num / 2:
smallest_num /= 2

Differentiating Python variables as str or int

I have a file that has 3 values on each line. It is a fairly random file, and any of these values can be str or int.
George, 34s, Nikon
42, absent, Alan
apple, 111, 41
marked, 15, never
...
So, I read in the line, and using split I get the first value:
theFile = r"C:\... "
tDC = open(theFile, "r")
for theLine in tDC:
a, b, c = theLine.split(',')
So far so good.
Where I'm stuck is when I try to deal with variable a. I need to deal with it differently if it is a str or if it is an int. I tried setting a = int(a), but if it is a string (e.g., 'George') then I get an error. I tried if type(a) = int or if isinstance(a,int), but neither work because all the values come in as a string!
So, how do I evaluate the value NOT looking at its assigned 'type'? Specifically, I want to read all the a's and find the maximum value of all the numbers (they'll be integers, but could be large -- six digits, perhaps).
Is there a way to read in the line so that numbers come in as numbers and strings come in as strings, or perhaps there is a way to evaluate the value itself without looking at the type?
The first point is that you need some rule that tells you which values are integers and which ones aren't. In a data set that includes things like 32s, I'm not sure it makes sense to just treat anything that could be an integer as if it were.
But, for simplicity, let's assume that is the rule you want: anything that could be an integer is. So, int(a) is already pretty close; the only issue is that it can fail. What do you do with that?
Python is designed around EAFP: it's Easier to Ask Forgiveness than Permission. Try something, and then deal with the fact that it might fail. As Cyber suggests, with a try statement:
try:
intvalue = int(a)
except ValueError:
# Oops, it wasn't an int, and that's fine
pass
else:
# It was an int, and now we have the int value
maxvalue = max(maxvalue, intvalue)
isalpha() Returns "True" if all characters in the string are in the alphabet
isnumeric() Returns "True" if all characters in the string are numeric
so;
data="Hello World"
print(data.isnumeric()) #it will retuns with False
print(data.isalpha()) # True
Sorry for my soulles answer, I just came here for same issue, I found a different way and wanted to share with you
values = theLine.split(',')
for value in values:
try:
number = int(value)
# process as number
except ValueError:
# process value as string
this :
def ret_var(my_var: int) -> int:
try:
intvalue = int(my_var)
return my_var
except ValueError:
print("my_var not int!")

Parameter in Python

Let's say there is a parameter n. Can n be any numbers? For example, question like this: Given a non-negative number num, return True if num is within 2 of a multiple of 10. This is what I am thinking:
def near_ten(num):
n = int #So I assume n can be any integer
if abs(num - n*10) <=2:
return True
Return False
However, there are two problems. First, in n*10, * is a unsupported operand type cuz I thought I could use Python as a calculator. 2nd, I cannot just simply say n = int, then n can be viewed as a variable as any number (or integer) in a math function. If there is a way that I could use n in that way, then life would be so much easier.
Finally I figure it out in another way which doesn't include "n" as a parameter:
def near_ten(num):
if num%10<=2:
return True
if (num+2)%10<=2:
return True
return False
However, I'm still curious about "n" as a parameter mentioned before. Since I'm just a starter, so this is really confusing.
In Python, int is a type. Types are first-class objects in Python, and can be bound to names. Of course, trying to multiply a type by a number is usually meaningless, so the operation is not defined by default. It can be referred to by the new name though.
n = int
print(n(3.4))
print(n('10') == 10)
Here is a much simpler solution:
def near_mult_ten(num):
return abs(num - (num+5) // 10 * 10) <= 2
Edit: Fixed.
try this:
d=a%10
if d<=2 or d>=8:
return True
return False
I am new to coding as well so forgive any mistakes.
i am not sure if you have ran your code or not, but python is a high level interpreted language, python CAN distinguish between variable types and therefore you do not need to explicitly declare them, your function header is valid.
you can also do operations between integers and floats/doubles without the need of casting, python already handles that for you
your function will raise an error in any compiler, ur n variable is declared, you have defined it, but you have not initialized it

Categories

Resources