How to compare float and decimal in python? - python

I have a (decimal.Decimal) column in a dataframe as below:
dt = pd.DataFrame({"OPEN": [-0.00010,-0.0114, 0.0066,-0.0044,-0.0012,-0.0005,
0.0005,-0.0037, -0.0029, 0.0034, 0.0003, 0.0001 ]})
dt["OPEN"] = dt["OPEN"].apply(Decimal)
and I would like to apply the following method over the Open column:
def label_change_price(delta):
if 0 < abs(delta) < 0.0001:
print(" Return value: ",0, "Delta: ",delta)
return 0
elif 0.0001 <= abs(delta) < 0.0002:
print(" Return value: ",1, "Delta: ",delta)
return int(np.sign(delta)) * 1
elif 0.0002 <= abs(delta) < 0.0003:
print(" Return value: ",2, "Delta: ",delta)
return int(np.sign(delta)) * 2
elif 0.0003 <= abs(delta):
print(" Return value: ",3, "Delta: ",delta)
return int(np.sign(delta)) * 3
When i run the code, for the very first row (-0.00010) it print
Return value: 0 Delta: -0.00010
which is wrong, as it must return 1, however it returns 0.
In other word, the first condition in if comes True and it does not continue to the second elif.
So, I am wondering, why my second elif 0.0001 <= abs(delta) < 0.0002: is not working well, when the delta is 0.0001 ? And how i can fix it ?

You might try comparisons like this:
if abs(Decimal(0)) < abs(delta) < abs(Decimal(0.0001)):
Comparisons seem tricksy:
from decimal import Decimal
Decimal(0.0001) == 0.0001
# True
abs(Decimal(0.0001)) == 0.0001
# False
Decimal(0.0001) == Decimal(0.0001)
# True
abs(Decimal(0.0001)) == Decimal(0.0001)
# False
abs(Decimal(0.0001)) == abs(Decimal(0.0001))
# True

Related

Converting hexadecimal to binary example

I do not seem to understand the error of this code. I am trying to convert from hexadecimal to decimal. For example for a hexadecimal string that starts with 0x. Can someone help me, please? Thank you
def hex_char_decode(digit): # 0xbadf00d
if digit[0:2] == "0x":
digit = digit[2:]
bit_index = len(digit) - 1
sum = 0
i = 0
while bit_index >= 0:
if digit[len] >= "0" and digit[len] <= "9":
res = int(digit[len])
elif digit[len] >= "A" and digit[len] <= "F":
res = ord(digit[len]) - 55
elif hex[len] >= 'a' and hex[len] <= 'f':
res = ord(digit[len]) - 87
else:
sum = 1
break
sum += (res * (16 ** i))
bit_index -= 1
i += 1
return sum
if __name__ == "__main__":
# you should have all your main logic including inputs.
# function calls and output inside of if statement.
hexa = input()
result = hex_char_decode(hexa)
print(result)

Python Perfect Number

In this Python Question, I should get False if the the number is not perfect. instead, I'm getting "None". What should I change?
def perfect(number):
sum = 0
is_perfect = False
if number < 0:
return is_perfect
for i in range(1, number):
if(number % i == 0):
sum = sum + i
if (sum == number):
is_perfect = True
return is_perfect
print(perfect(8))
You should return False at the End otherwise None is getting returned implicitly:
def perfect(number):
...
for i in range(1, number):
...
return False
Hi your problem is that you have no return when you don't match if (sum == number):..
so, the simplest solution is to add an return False at the end. But also your sum condition is inside the for that's not fine because you can encounter a fake perfect
like 24... so be carefull about that condition
edit 0 is not a perfect number so add the condition to first if
def perfect(number):
sum = 0
is_perfect = False
if number <= 0:
return is_perfect
for i in range(1, number):
if(number % i == 0):
sum = sum + i
if (sum == number):
is_perfect = True
return is_perfect
return False
I would totally reshape your code to make it a litle more clear:
def is_perfect(number):
acum= 0
if number <= 0:
return False
for i in range(1, number):
if(number % i == 0):
acum += i
return (acum == number) #return true if the condition match, False if not
#just to check function
print([(i,is_perfect(i)) for i in range(1,100) if is_perfect(i)])
#output
[(6, True), (28, True)]

Newton Recursive Method for Square Root Problem in Python

For a=13 and a precision epsilon=10^-7. How many times do you apply the newton recursion formula in newton_sqrt(13,10^-7)? Hint: use global variables.
My current newton_sqrt(a, epsilon) function is the following:
def newton_sqrt(a, epsilon):
global count
if a < 0:
print("Error: a < 0")
return -1
elif a == 0.0:
return 0
else:
x = abs(a)
newx = 0.5*(x + a/x)
if abs(x - newx) > epsilon:
newton_sqrt(newx, epsilon)
count = count + 1
if not abs(x-newx) > epsilon:
print (count)
return newx
newton_sqrt(13, 0.000001)
For whatever reason, I get
918488688 None
as my output.
Please help.
There is no output since you never reach the print line:
basically, you have:
if x:
if not x:
print(something)
what you want, i'm guessing is:
if x:
#do something
else:
#do somthing else
not knowing the math of your function I would change it into:
def newton_sqrt(a, epsilon, count):
if a < 0:
print("Error: a < 0")
return -1
elif a == 0.0:
return 0
else:
x = abs(a)
newx = 0.5*(x + a/x)
if abs(x - newx) > epsilon:
count = count + 1
newton_sqrt(newx, epsilon, count)
else:
print (count)
return newx
which will give you:
newton_sqrt(13, 0.000001, 0)
23
First, let's be clear that your newton_sqrt() function doesn't work. Either you're trying to instrument the recursion depth to fix it, or you're unaware it's broken.
A working newton_sqrt() would be along the lines of:
import sys
def newton_sqrt(a, epsilon, x=None):
if a < 0:
print("Error: a < 0", file=sys.stderr)
return -1
if a == 0:
return 0
if x is None: # initial guess
x = a
new_x = (x + a / x) / 2 # refine guess
if abs(new_x * new_x - a) < epsilon: # test guess
return new_x
return newton_sqrt(a, epsilon, new_x) # (better) guess again
print(newton_sqrt(13, 1e-06))
Once that's working, instrumenting the recursion depth using a global variable, count, is simple:
import sys
count = 0
def newton_sqrt(a, epsilon, x=None):
global count
count += 1
if a < 0:
print("Error: a < 0", file=sys.stderr)
return -1
if a == 0:
return 0
if x is None: # initial guess
x = a
new_x = (x + a / x) / 2 # refine guess
if abs(new_x * new_x - a) < epsilon: # test guess
return new_x
return newton_sqrt(a, epsilon, new_x) # (better) guess again
print(newton_sqrt(13, 1e-06), count)
OUTPUT
> python3 test.py
3.6055513629176015 5
>
Where 3.6055513629176015 is the square root of 13 and 5 is the recursion depth needed to compute it with an error of less than 1e-06.

Binary Subtraction - Python

I want to make a binary calculator and I have a problem with the subtraction part. Here is my code (I have tried to adapt one for sum that I've found on this website).
maxlen = max(len(s1), len(s2))
s1 = s1.zfill(maxlen)
s2 = s2.zfill(maxlen)
result = ''
carry = 0
i = maxlen - 1
while(i >= 0):
s = int(s1[i]) - int(s2[i])
if s <= 0:
if carry == 0 and s != 0:
carry = 1
result = result + "1"
else:
result = result + "0"
else:
if carry == 1:
result = result + "0"
carry = 0
else:
result = result + "1"
i = i - 1
if carry>0:
result = result + "1"
return result[::-1]
The program works fine with some binaries subtraction but it fails with others.
Can someone please help me because I can't find the mistake? Thanks a lot.
Short answer: Your code is wrong for the case when s1[i] == s2[i] and carry == 1.
Longer answer: You should restructure your code to have three separate cases for s==-1, s==0, and s==1, and then branch on the value of carry within each case:
if s == -1: # 0-1
if carry == 0:
...
else:
...
elif s == 0: # 1-1 or 0-0
if carry == 0:
...
else:
...
else: # 1-0
if carry == 0:
...
else:
...
This way you have a separate block for each possibility, so there is no chance of overlooking a case like you did on your first attempt.
I hope the answer below it helps.
def binarySubstration(str1,str2):
if len(str1) == 0:
return
if len(str2) == 0:
return
str1,str2 = normaliseString(str1,str2)
startIdx = 0
endIdx = len(str1) - 1
carry = [0] * len(str1)
result = ''
while endIdx >= startIdx:
x = int(str1[endIdx])
y = int(str2[endIdx])
sub = (carry[endIdx] + x) - y
if sub == -1:
result += '1'
carry[endIdx-1] = -1
elif sub == 1:
result += '1'
elif sub == 0:
result += '0'
else:
raise Exception('Error')
endIdx -= 1
return result[::-1]
normalising the strings
def normaliseString(str1,str2):
diff = abs((len(str1) - len(str2)))
if diff != 0:
if len(str1) < len(str2):
str1 = ('0' * diff) + str1
else:
str2 = ('0' * diff) + str2
return [str1,str2]

Maximum recursion depth exceeded in python for calculates the exponential

I have tried this version is correct:
def recurPowerNew(base, exp):
if exp == 0:
return 1
elif exp > 0 and exp % 2 == 1:
return base * recurPowerNew(base, exp-1)
elif exp > 0 and exp % 2 == 0:
return recurPowerNew(base * base, exp / 2)
while this version appears error:
def recurPowerNew(base, exp):
if exp == 0:
return 1
elif exp > 0 and exp % 2 == 1:
return base * recurPowerNew(base, exp-1)
elif exp > 0 and exp % 2 == 0:
return recurPowerNew(recurPowerNew(base, 2), exp / 2)
The difference is the last elif.
Can anyone figure out why?
On the last elif in the second version, you are calling your recursive function with itself as an argument. This is leading to recursion within recursion, which will run so many times that it exceeds the maximum recursion depth.

Categories

Resources