Python print questions related to float - python

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.

Related

How to keep leading zero when returning value from modulo Python

I want to build a program which allows the user to input a number then make that number exponent of 2. Also user inputs how many last digits of final number wants to see. This is my code:
exponent = eval(input('Type in exponent '))
lastDigits = eval(input('Type in how many digits you want to see'))
number = 2**exponent
print(number /int(('1'+('0'*lastDigits))))
The output for example is:
Type in exponent = 10
Type in how many digits you want to see = 3
Here comes the problem.
If my exponent is 10 that means 2**10 = 1024
I want to see 3 last digits so that is 024 but Python doesn't keep this leading zero so I just get 24. How can I fix this?
I would use string operations instead of integer operations:
exponent = int(input('Type in exponent '))
lastDigits = int(input('Type how many digits you want to see '))
number = 2 ** exponent
cropped = str(number)[-lastDigits:]
print(cropped) # Result: "024"
I'm essentially just slicing off all but the last lastDigits characters in the string representation of number, that way we include any leading zeroes.
I also switched to using int casting instead of the eval function, because the eval function could be potentially dangerous if anyone decides to put something destructive into the input.

Python round function not working as expected

In Python, round(0.625) returns 0.62. why is this?
The following code only applies for positive numbers, what are better alternative?
from maths import floor
def round2Dp(n, decimals=0):
multiplier = 10 ** decimals
return floor(n*multiplier+0.5) / multiplier
See the documentation for numeric types here. Specifically:
round(x[, n]): x rounded to n digits, rounding half to even. If n is omitted, it defaults to 0.
This basically means that half (0.5) is always rounded to the nearest even number.
GeeksForGooks.com says, "When the second parameter is present, then it returns:
The last decimal digit till which it is rounded is increased by 1 when (ndigit+1)th digit is >=5 , else it stays the same."
Somebody tried to reject this answer, saying that he was pretty sure that was not what the web site said. This was a direct cut and paste from this page: https://www.geeksforgeeks.org/round-function-python/

Count the order of the last digit of a number in Python

Hy everybody,
I'm trying to write a program with Python that tells me the order of the last digit of a number: for example if the number is 230 then the answer is 1, for 0.104 it is 0.001, for 1.0 it is 0.1 and so on... I've tried to write something but it does strange things for float numbers: it is approximately right for numbers that do not end with 0, and it is wrong for those ending with 0. This is what I wrote:
def digit(x):
if (x-int(x))==0:
return 1
else:
return 0.1*digit(x*10)
Thanks to anybody who will answer.
You could use decimal.Decimal to obtain the amount of decimal places, and compute the order of the last digit as 1e^x, x can be obtained through the exponent attribute of the named tuple returned by decimal.Decimal.as_tuple():
import decimal
def order_last_digit(d):
dec = decimal.Decimal(str(d))
return 10**dec.as_tuple().exponent
order_last_digit(230) #10^0=1
# 1
order_last_digit(0.104) #10^-3
# 0.001
order_last_digit(1.0)
# 0.1
it seems the first part of your code works right so i didn't touch it.
def digit(x):
if (x-int(x))==0:
return 1
else:
return '0.'+''.join(['0' for i in str(x).split('.')[1][0:-1]]+['1'])

Converting Binary to Decimal in python (without built in binary function)

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.

How to identify the tenths part of a float in Python?

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

Categories

Resources