After looking at the various math, float, and decimal functions in Python, I haven't found what I'm looking for. In my program, there may be instances when it will return a float and I need the float information so that I can do another function. Let's say based on the user's input the quotient we're working with is 1.4, which I will represent as X.Y. How do I isolate Y so that I can use a FOR statement. (I need the program to do something 4 times in this case.) I've tried playing with the % function, but that returns the remainder, not the value I'm looking for. I've tried math.fmod and math.modf. Again not what I'm looking for. I looked at this example too.
Looks like int((x*10) % 10) will do it:
>>> x = 1.4
>>> int((x*10) % 10)
4
How about
x = 1.4
y = 10 * (x - int(x))
>>> 4
or you could do it as string manipulation
x=1.4
whole,fractional = map(int,str(x).split("."))
afterwards whole is equal to 1 and fractional is equal to 4... and it should work equally well with negative numbers
Using the following method you can get any position in a float. That is, tenths, hundredths, thousandths and so on:
import math
def get_pos_float(num, unit):
if unit >= 10:
num = abs(math.modf(num)[0]) # Get just the fractional part
num *= 10 # Move the decimal point one place to the right
return get_pos_float(num, unit/10)
return int(math.modf(num)[1]) #Return the whole number part
decimalNumber = 13.24
print(get_pos_float(decimalNumber, 10)) # prints the tenths decimal position 2
print(get_pos_float(decimalNumber, 100)) # prints the hundredths decimal position 4
print(get_pos_float(decimalNumber, 1000)) # prints the thousandths decimal position 0
Related
I have a python code that when given a small number between 0 and 1 doesn't print it fully, but 4.43017984825e-7 for example,how do I make the code shows the whole number with all zeroes?
this was my try:
number="4.43017984825e-7"
result=number.find("e")
new=list(number)
last=int(new[-1])
print(last)
del new[13:16]
print(new)
pricee=(''.join(new))
print(pricee)
price=float(pricee)*10**-(last)
print(price)
Note: the number changes everytime, so I want it to be applicable for all numbers.
You can probably accomplish what you want with fixed-point formatting.
>>> x=4.43017984825e-7
>>> print(x)
4.43017984825e-07
>>> print(f"{x:20.18f}")
0.000000443017984825
The 20 in that format tells the full width you want, while the 18 tells the number of decimals.
Now, this is fairly specific to this number, you'll have to pick the right length and number of decimals for your actual application.
Expanding on the suggestion from #MostafaFarzán: you can use log10 to adjust that fixed point formatting to any number:
x = <some float>
significant_digits = 8
decimals=max(0, int(-log10(x) + significant_digits))
print(f"%.{decimals}f" % x)
or, more concisely but harder to read:
print(f"%.{max(0, int(-log10(x) + 8))}f" % x)
1.45
4
Hey everyone i need to print number right of the decimal point like if i input 1.45 it needs to output 4 because its first number after point i also tried multiplying by 10 or 100 but i dont know much numbers will be after point so if there is 3 numbers after point youn still need to print the first number after point. I have tried using ".2f" which didnt work it just made things worse i also tried finding things in internet all i found was about ".2f".
You could just multiply by 10, ignore any fractional component by converting to int then print the value modulus 10. Like this:
n = 1.45
print(int(n * 10) % 10)
Output:
4
Use format with a floating-point format specifier to convert a number to a string:
x = 1.45
'{:f}'.format(x) # '1.45'
(the format specifier is needed to avoid using scientific notation like
1e-09)
Use split to find the fractional part:
x = 99
'{:f}'.format(x).split('.') # ['99', '000000']
Take the second part from the list:
x = -3.1415
'{:f}'.format(x).split('.')[1] # '141500'
Then take the first character:
x = 1.45
print('{:f}'.format(x).split('.')[1][0]) # 4
With a slight modification, this will work to extract any decimal digit:
x = 0.000000000001234
print('{:20f}'.format(x).split('.')[1][12]) # 12th decimal is 2
Here, I used 20 to generate enough decimals (default is 6).
print("%.5f" % 5.1234567890) output is 5.12346
i am not understanding why 5 is not printed in output in precision field. after 4 the 6 is printed directly. why?
You limit the number of digits in fractional part to 5 digits. When you do that it rounds the number up or down based on number after the last digit. In your case, the fifth digit of the fractional part is 5 and after that is 6. So it rounds the number 5 up.
The number you type after the dot limits the float digits after the decimal point. so your command will prints the number and the first 5 digits of his decimal part.
I don't think there is anything in the math library to do this, since obviously normal people would round that number up.
But if you are really trying to round down, for whatever reason, you would need to build a function or import some other library someone else made to do it.
You can also create a function do it, for example:
import math
def round_decimals_down(number:float, decimals:int=2):
if not isinstance(decimals, int):
raise TypeError("A")
elif decimals < 0:
raise ValueError("B")
elif decimals == 0:
return math.floor(number)
factor = 10 ** decimals
return math.floor(number * factor) / factor
valueA = 5.1234567890
roundA = round_decimals_down(valueA, 5)
print(roundA)
output: 5.12345
Let me know if that is what you were trying to accomplish.
I have some number 0.0000002345E^-60. I want to print the floating point value as it is.
What is the way to do it?
print %f truncates it to 6 digits. Also %n.nf gives fixed numbers. What is the way to print without truncation.
Like this?
>>> print('{:.100f}'.format(0.0000002345E-60))
0.0000000000000000000000000000000000000000000000000000000000000000002344999999999999860343602938602754
As you might notice from the output, it’s not really that clear how you want to do it. Due to the float representation you lose precision and can’t really represent the number precisely. As such it’s not really clear where you want the number to stop displaying.
Also note that the exponential representation is often used to more explicitly show the number of significant digits the number has.
You could also use decimal to not lose the precision due to binary float truncation:
>>> from decimal import Decimal
>>> d = Decimal('0.0000002345E-60')
>>> p = abs(d.as_tuple().exponent)
>>> print(('{:.%df}' % p).format(d))
0.0000000000000000000000000000000000000000000000000000000000000000002345
You can use decimal.Decimal:
>>> from decimal import Decimal
>>> str(Decimal(0.0000002345e-60))
'2.344999999999999860343602938602754401109865640550232148836753621775217856801120686600683401464097113374472942165409862789978024748827516129306833728589548440037314681709534891496105046826414763927459716796875E-67'
This is the actual value of float created by literal 0.0000002345e-60. Its value is a number representable as python float which is closest to actual 0.0000002345 * 10**-60.
float should be generally used for approximate calculations. If you want accurate results you should use something else, like mentioned Decimal.
If I understand, you want to print a float?
The problem is, you cannot print a float.
You can only print a string representation of a float. So, in short, you cannot print a float, that is your answer.
If you accept that you need to print a string representation of a float, and your question is how specify your preferred format for the string representations of your floats, then judging by the comments you have been very unclear in your question.
If you would like to print the string representations of your floats in exponent notation, then the format specification language allows this:
{:g} or {:G}, depending whether or not you want the E in the output to be capitalized). This gets around the default precision for e and E types, which leads to unwanted trailing 0s in the part before the exponent symbol.
Assuming your value is my_float, "{:G}".format(my_float) would print the output the way that the Python interpreter prints it. You could probably just print the number without any formatting and get the same exact result.
If your goal is to print the string representation of the float with its current precision, in non-exponentiated form, User poke describes a good way to do this by casting the float to a Decimal object.
If, for some reason, you do not want to do this, you can do something like is mentioned in this answer. However, you should set 'max_digits' to sys.float_info.max_10_exp, instead of 14 used in the answer. This requires you to import sys at some point prior in the code.
A full example of this would be:
import math
import sys
def precision_and_scale(x):
max_digits = sys.float_info.max_10_exp
int_part = int(abs(x))
magnitude = 1 if int_part == 0 else int(math.log10(int_part)) + 1
if magnitude >= max_digits:
return (magnitude, 0)
frac_part = abs(x) - int_part
multiplier = 10 ** (max_digits - magnitude)
frac_digits = multiplier + int(multiplier * frac_part + 0.5)
while frac_digits % 10 == 0:
frac_digits /= 10
scale = int(math.log10(frac_digits))
return (magnitude + scale, scale)
f = 0.0000002345E^-60
p, s = precision_and_scale(f)
print "{:.{p}f}".format(f, p=p)
But I think the method involving casting to Decimal is probably better, overall.
Alrighty, first post here, so please forgive and ignore if the question is not workable;
Background:
I'm in computer science 160. I haven't taken any computer related classes since high school, so joining this class was a big shift for me. It all seemed very advanced. We have been working in Python and each week we are prompted to write a program.
I have been working with this problem for over a week and am having a hard time even starting.
The prompt is to read an integer containing only 1's and 0's,
process the binary number digit by digit and report the decimal equivalent. Now, I have gotten some tips from a classmate and it sent me at least in a direction.
Set up a couple of counters;
using the % operator to check the remainder of the number divided by 2, and slicing off the last number (to the right) to move on to and process the next digit.
I am having an incredibly hard time wrapping my head around what formula to use on the binary digits themselves which will convert the number to decimal.
setbitval = 0
counter = 0
user = int(input("enter a binary value. "))
if user % 2 == 1:
user = (user/10) - .1
setbitval += 1
This is all I've got so far.. My thinking is getting in the way. I've searched and searched, even through these forums.
Any information or thoughts are extremely appreciated,
T
Edit: okay guys, everyone's help has been extremely useful but I'm having a problem checking if the user input is not a binary number.
for i in reversed(bits):
decimal += 2**counter * int(i)
counter += 1
This is the formula someone here gave me and I've been trying different iterations of "for i in bits: if i in bits: != 0 or 1" and also "if i in bits: >= 1 or <=0".
Any thoughts?
you can use this code:
binary= raw_input("Binary: ")
d= int(binary, 2)
print d
To convert binary value to decimal you need to do the following:
Take the least significant bit and multiply it by 2^0, then take the next least significant beat and multiply it by 2^1, next one by 2^2 and so on...
Let's say, for example you need to convert a number 1010 to decimal:
You would have 0*2^0 + 1*2^1 + 0*2^2 + 1*2^3 = 0 + 2 + 0 + 8 = 10
So in your python code, you need to:
read the int that the user inputted (representing the binary value).
convert that int and convert it to string, so you can break it into list of digits
make a list of digits from the string you created (a list int python can be created from a string not an int, that's why you need the conversion to string first)
go trough that list of bits in reverse and multiply every bit by 2^k, k being the counter starting from 0
Here's the code that demonstrates what I just tried to explain:
user_input = int(input("enter a binary value"))
bits = list(str(user_input))
decimal = 0
counter = 0
for i in reversed(bits):
decimal += 2**counter * int(i)
counter+=1
print 'The decimal value is: ', decimal
I'll agree this is close to the "code this for me" territory, but I'll try to answer in a way that gets you on the right track, instead of just posting a working code snippet.
A simple way of doing this is just to use int()'s base argument, but I'm guessing that is disallowed.
You already have a way of testing the current bit in your question, namely checking whether n % 2 == 1. If this is the case, we need to add a power of two.
Then, we need some way of going to the next bit. In binary, we would use bit shifts, but sadly, we don't have those. a >> b is equivalent to a // (2**b) - can you write a decimal equivalent to that?
You also need to keep a counter of which power of two the current bit represents, a loop, and some way of detecting an end condition. Those are left as exercises to the reader.
I’d recommend reading the following articles on Wikipedia:
https://en.wikipedia.org/wiki/Radix
https://en.wikipedia.org/wiki/Binary_number
The first one gives you an idea how the numeral systems work in general and the second one explains and shows the formula to convert between binary and decimal systems.
Try to implement the solution after reading this. That’s what I did when I dealt with this problem. If that doesn’t help, let me know and I’ll post the code.
Hopefully, this code clarifies things a bit.
x = input("Enter binary number: ").strip()
decimal = 0
for i in range(len(x)):
decimal += int(x[i]) * 2**abs((i - (len(x) - 1)))
print(decimal)
This code takes in a binary number as a string, converts it to a decimal number and outputs it as an integer. The procedure is the following:
1st element of binary number * 2^(length of binary number - 1)
2nd element of binary number * 2^(length of binary number - 2)
and so on till we get to the last element and ...2^0
If we take number 10011, the conversion using this formula will look like this:
1*2^4 + 0*2^3 + 0*2^2 + 1*2^1 + 1*2^0, which equals to 19.
This code, however, assumes that the binary number is valid. Let me know if it helps.
Another implementation using while loop might look like this. Maybe it'll be easier to understand than the code with the for loop.
x = input("Enter binary number: ").strip()
decimal = 0
index = 0
exp = len(x) - 1
while index != len(x):
decimal += int(x[index]) * 2**exp
index += 1
exp -= 1
print(decimal)
In this one we start from the beginning of the number with the highest power, which is length of binary number minus one, we loop through the number, lowering the power and changing index.
Regarding checking if number is binary.
Try using helper function to determine if number is binary and then insert this function inside your main function. For example:
def is_binary(x):
""" Returns True if number x is binary and False otherwise.
input: x as a string
"""
for i in list(x):
if i not in ["1", "0"]:
return False
return True
def binary_decimal(x):
""" Converts binary to decimal.
input: binary number x as a string
output: decimal number as int
"""
if not is_binary(x):
return "Number is invalid"
decimal = 0
for i in range(len(x)):
decimal += int(x[i]) * 2**abs((i - (len(x) - 1)))
return decimal
The first function checks if number consists only of ones and zeros and the second function actually converts your number only if it's binary according to the first function.
You can also try using assert statement or try / except if you'd better raise an error if number is not binary instead of simply printing the message.
Of course, you can implement this solution without any functions.