Extract decimal part of a floating point number - python

I have a function that takes a float as an input and the output is only the decimal part.
For example, get_decimal(4.45) should return 0.45, and we should only return positive figures.
I made the following code:
def get_decimal(n):
try:
return float('0.'+(str(n).split('.',1))[1])
except:
return 0
And this code almost works, but it doesn't give the whole answer.
For example get_decimal(4.566666678258757587577) only returns:
0.566666678258757
instead of:
0.566666678258757587577
Is there a way to get the whole number?

Use the modulus:
inp = 4.566666678258757587577
output = inp % 1
print(output) # prints 0.566666678259
Note that Python's print() function usually attempts to display a more human readable form of a floating point number. So, while the printed value appears to stop after 12 digits, there is more precision beyond that not shown.
Consider:
print((output * 100000) % 1) # prints 0.667825875724
# 4.566666678258757587577 <- original input

you can try this :
output = round(inp-int(inp),abs(decimal.Decimal(str(inp)).as_tuple().exponent)

you can use Decimal but in that case you need to set your input as string:
from decimal import *
def get_decimal(n):
try:
return Decimal('0.'+(str(n).split('.',1))[1])
except:
return 0
print(get_decimal("4.5666666782587575875779"))
output:
0.5666666782587575875779

Related

Recursive decimal to binary converter in python

def toBinary(decimal, binaryList):
if decimal <= 1:
return binaryList
else:
decimal = decimal //2
return toBinary(decimal, binaryList)
binaryList.append(decimal %2)
The functions returns empty brackets instead of printing the binary number as a list.
Your code is on the right track but has issues. First is what #KlausD comments, no line directly after a return gets executed. So the order of statements is at issue. Next, the variable binaryList doesn't get initialized in your provided code fragment. It could get initialized by the caller:
array = toBinary(13, []):
which works, but the caller might find it strange. We could intialize it using a default:
def toBinary(13, binaryList=[]):
But as a container type, that would constitute a dangerous default which we want to steer clear of. We could safely initialize it to None as a default and reinitialize it later in the code:
def toBinary(decimal, binaryList=None):
# ...
if binaryList is None:
binaryList = []
Which is safe and hides this argument from the caller. Next, by dividing, we're analyzing our decimal digits from right to left, so we need to build up our binary number in the same direction, thus append():
binaryList.append(decimal % 2)
is a problem as it builds up the binary result from left to right. We could end with a revese() but it's probably better to use binaryList.insert(0, ...) to build in the proper direction. Finally, this is a special case:
array = toBinary(0)
as we're going to use a zero argument to trigger end of recursion but how it affects our result (i.e. not at all) is different than if we're passed zero from the get-go (i.e. return a [0]). Here's my rework of your code that addresses all of these issues:
def toBinary(decimal, binaryList=None):
if decimal == 0:
return binaryList or [0]
if binaryList is None:
binaryList = []
binaryList.insert(0, decimal % 2)
return toBinary(decimal // 2, binaryList)
print(toBinary(13))
OUTPUT
> python3 test.py
[1, 1, 0, 1]
>
It is better not to return binary list.
def toBinary(decimal, binaryList):
if decimal <= 0:
return
else:
toBinary(decimal//2, binaryList)
binaryList.append(decimal %2)
This code also converts to Binary. It can also convert into other bases. Just change the parameter base, to the base you want.
import string
def to_base(value, base=2): # converts decimal to base n
string_slice = string.printable[0:base]
data_dict = {}
for each_character, each_number in zip(string_slice, range(base)):
data_dict.update({each_character: each_number})
data = []
temporary_var = value
data.append(temporary_var)
while True:
temporary_var = temporary_var // base
data.append(temporary_var)
if temporary_var < base:
break
else:
continue
result = ''
for each_data in data:
result += list(data_dict.keys())[each_data % base]
result = result[::-1]
return result by
My code may not be perfect. Feel free to suggest improvements.
print(to_base(5, base=2)) # Outputs : 101. Because 101 is 5 in binary
print(to_base(17, base=16)) # Outputs : 11. Because 11 is 17 in hexadecimal

Converting binary number to decimal useing string

I've tried to write a simple function, which input is binary number in string format and converts binary to decimal. But in the output I always get the wrong thing: the 'res' value in line 3, no matter what the input is ('1010', '10010111010', etc.). Also, I've tried to debug the code and the function doesn't even start the loop, as if it wasn't there... So, I just don't see my mistake
def bin_to_dec(bin):
bin = bin[::-1]
res = 0
for i in range(len(bin)):
if bin[i] == 0:
res += 2**i
return res
You are comparing the string "0" to the number 0 and they are, trivially, unequal.
So, contrary to what you say, the loop is actually looping; but the if statement will never be true.
Of course, also, you should probably add when the number is 1, not when it's 0.
def bin_to_dec(bin):
bin = bin[::-1]
res = 0
for i in range(len(bin)):
if int(bin[i]) == 1:
res += 2**i
return res
Notice the addition of int().
if bin[i] == '1'
This will correct the problem. bin[i] is a character and you are comparing it to a number which always results in false.
You can just use the built in int function:
def binaryToDecimal(n):
return int(n,2)

Python math division operation returns 0

print "------------ EPIDEMIOLOGY --------------\n"
def divide(A,B):
return A/B
print " [Population] point Prevalence rate: "
A = input("Enter value for people with disease: " )
B = input("Enter value for total population: " )
prevalence = divide(A,B)
print " Population Prevalence rate is: ",prevalence
A and B are user input and do not know if they are integers or floats. My answer is always 0 when i run this program. (I'm new in Python). How do i fix this or change in my function to avoid this problem?
the input part of code works, the math does not.
You get the answer 0 because you are using Python2 and performing integer division. The fact that the population with disease cannot be higher than the total population is the reason that you get zero for every reasonable input (except when both values are the same).
Two fixes:
def divide(a,b):
if b == 0:
# decide for yourself what should happen here
else:
return float(a)/b
This will make sure that your function performs floating point division, not matter what numbers you pass to it. The second fix is that you should use raw_input in Python2 and cast the input to a number (float would be fine here).
a = float(raw_input("Enter value for people with disease: ")) # add error checking as needed
b = float(raw_input("Enter value for total population: " )) # add error checking as needed
The problem with input() is that it is equivalent to eval(raw_input()).
In python 2.x is performed integer division. If dividend is less than divisor, the operation returns zero.
So you have two options:
Make one of operands as float:
def divide(A,B):
return float(A)/B
import feature from Python 3
from __future__ import division
print "------------ EPIDEMIOLOGY --------------\n"
def divide(A,B):
return A/B

How to define new variable as float?

I'm trying to make the following function output the correct answer, but the 'rightSide' variable is being made as an integer, and doesn't have any decimals.
def G(mass1, mass2, radius, force):
rightSide=(mass1*mass2)/(radius**2) #I want this to be a float
print rightSide
if rightSide==0:
print("The operation resulted in a zero, error!")
else:
answer=force/rightSide
print(str(answer)+" is the gravitation constant (G)!")
I just want all the variables to be floats, but the problem starts with 'rightSide'.
I tried the following with no success:
float(rightSide)=(mass1*mass2)/(radius**2)
--
rightSide=(float(mass1)*float(mass2))/(float(radius)**2)
Any tips? Thanks!
Nevermind, I just re-ran the second code that I hand typed in the question and it worked -_-
In general
x = float(2)
Or
y = 10
x = float(y)
In your case,
rightSide=float((mass1*mass2)/(radius**2))
You need to make one of the inputs a floating point value. Try changing 2 to 2.0. E.g.:
>>> x=10
>>> x**2
100
>>> x**2.0
100.0
Note that in Python 3 division automatically returns a floating point, and the new // operator explicitly does integer division.
Try this:
def G(mass1, mass2, radius, force):
rightSide = (float(mass1)*mass2) / (radius**2) #I want this to be a float
print rightSide
if rightSide==0:
print("The operation resulted in a zero, error!")
else:
answer=force/rightSide
print(str(answer)+" is the gravitation constant (G)!")

python: float number like integer

I try convert a float to int when the number don't have decimals.
I make this
from math import modf
def float_like_int(n):
if abs(modf(n)[0]) < 1e-6:
return int(n)
return n
print float_like_int(10.1)
print float_like_int(10.00001)
print float_like_int(10.000001)
print float_like_int(10.0)
exist a standard function or a more general way ? (without 1e-6)
I think the following is a bit more readable than your version:
def float_like_int(n):
if round(n, 6) == round(n):
return int(round(n))
return n
Note that this does have a slightly different meaning than your function, since it would also round something like 9.9999999 to 10.
Those approach that you are using trys to make a number integer if a fractional part is less than 1e-6 (0.000001 ). This means if you have a number 4.000001, (which is float actually) your function will throw away fractional part. You can change 1e-6 to another value and those numbers, which meet your criteria will be converted to int.
Here is my code without any extra modules imported. This code will not throw away any fractional part.
def Func(a):
if (a * 10) % 10 == 0:
return int(a)
else:
return a
f = 4.03
print Func(23.45)
print Func(f)
print Func(2.3)
Maybe something like this is more natural?
def float_like_int(n):
if int(n) == float(n):
return int(n)
else:
return float(n)
You can use this function :
def isWhole(x):
if(x%1 == 0):
return True
else:
return False

Categories

Resources