I need to convert from binary values such as '1010' to decimal values. this needs to include negative binary.
def BinaryToDecimal (n):
n1 = n
decimal = 0
i = 0
n = 0
while(n != 0):
dec = n % 10
decimal = decimal + dec * pow(2, i)
n = n//10
i += 1
print(decimal)
This is what i have so far, but it doesn't work. I'm not sure what else to do. Please help! I am not allowed to use any fancy python libraries, I am supposed to write the code manually.
This will work:
def BinaryToDecimal(n):
n = str(n)
print(int(n,2))
Python shell output
Binary to decimal:
>>> bin_str = '11111111'
>>> int(bin_str,2)
255
Decimals to binary:
>>> decimal = 255
>>> "{:b}".format(decimal)
'11111111'
Related
Hopefully a simple one, I have a number, say 1234567.890 this number could be anything but will be this length.
How do I truncate the first 3 numbers so it turns into 4567.890?
This could be any number so subtracting 123000 will not work.
I'm working with map data in UTM coordinates (but that should not matter)
Example
x = 580992.528
y = 4275267.719
For x, I want 992.528
For y, I want 267.719
Note: y has an extra digit to the left of the decimal so 4 need removing
You can use slices for this:
x = 1234567.890
# This is still a float
x = float(str(x)[3:])
print(x)
Outputs:
4567.89
As [3:] gets the starts the index at 3 and continues to the end of the string
Update after your edit
The simplest way is to use Decimal:
from decimal import Decimal
def fmod(v, m=1000, /):
return float(Decimal(str(v)) % m)
print(fmod(x))
print(fmod(y))
Output
992.528
267.719
If you don't use string, you will have some problems with floating point in Python.
Demo:
n = 1234567.890
i = 0
while True:
m = int(n // 10**i)
if m < 1000:
break
i += 1
r = n % 10**i
Output:
>>> r
4567.889999999898
>>> round(r, 3)
4567.89
Same with Decimal from decimal module:
from decimal import Decimal
n = 1234567.890
n = Decimal(str(n))
i = 0
while True:
m = int(n // 10**i)
if m < 1000:
break
i += 1
r = n % 10**i
Output:
>>> r
Decimal('4567.89')
>>> float(r)
4567.89
This approach simply implements your idea.
int_len is the length of the integer part that we keep
sub is the rounded value that we will subtract the original float by
Code
Here is the code that implements your idea.
import math
def trim(n, digits):
int_len = len(str(int(n))) - digits # length of 4567
sub = math.floor(n / 10 **int_len) * 10**int_len
print(n - sub)
But as Kelly Bundy has pointed out, you can use modulo operation to avoid the complicated process of finding the subtrahend.
def trim(n, digits):
int_len = len(str(int(n))) - digits # length of 4567
print(n % 10**int_len)
Output
The floating point thing is a bit cursed and you may want to take Corralien's answer as an alternative.
>>> n = 1234567.890
>>> trim(n, 3)
4567.889999999898
def get_slice(number, split_n):
return number - (number // 10**split_n) * 10**split_n
I want to change some binary streams to decimal but I got not all arguments converted during string formatting. The point is I have the result when using binaryToDecimal (10100000) which 10100000 is the first value of my list. But when I use binaryToDecimal (instream_chunks[0]) which is my for loop I got the above error. How can I fix that?
I am new to python sorry for my simple question.......
def binaryToDecimal(binary):
binary1 = binary
decimal, i, n = 0, 0, 0
while(binary != 0):
dec = binary % 10
decimal = decimal + dec * pow(2, i)
binary = binary//10
i += 1
print(decimal)
instream = '1010000000011000000110000000001'
instream_chunks = [instream[i:i+8]for i in range (0, len(instream), 8)]
for i in range (len(instream_chunks)):
img_value = binaryToDecimal (instream_chunks[i])
You need to convert the strings to integers before using your function on them. Like so:
def binaryToDecimal(binary):
binary1 = binary
decimal, i, n = 0, 0, 0
while(binary != 0):
dec = binary % 10
decimal = decimal + dec * pow(2, i)
binary = binary//10
i += 1
print(decimal)
instream = '1010000000011000000110000000001'
instream_chunks = [instream[i:i+8]for i in range (0, len(instream), 8)]
for i in range (len(instream_chunks)):
img_value = binaryToDecimal (int(instream_chunks[i]))
I want to calculate square root of numbers and print them with exactly 4 numbers after decimal point without rounding.
This code rounds the numbers
num="%.4f" % num
and this one doesn't show 1.0000 or numbers like this.
num=math.floor(num * 10000)/10000
Here is an option if you wish printing / just showing the 4 numbers after decimal point:
num = 0.553252
'{:.4f}'.format(num)
You can find more information on presenting strings / values here -
https://pyformat.info/#number
Try this:
>>> num = 5.12129
>>> num = f'{num:.5f}'[:-1]
>>> num
'5.1212'
You could convert the number to a string, then use string manipulation:
def numberWithoutRounding(num, precision=4):
[beforeDecimal, afterDecimal] = str(num).split('.')
return beforeDecimal + '.' + afterDecimal[0:precision]
>>> numberWithoutRounding(1.43219)
'1.4321'
Move the significant digits to the left of the decimal point, truncate it with ‘int’ and them move them back.
num = float (int (num * 10000) / 10000)
print (num)
You can convert them into string. Here's a way -
num = str(0.5532523).split('.')
ans = '%s.%s' % (num[0], num[1][:4])
print(ans)
import math
tedad=int(input())
adadlist=[]
rishe=[]
for i in range(0,tedad):
adadlist.append(int(input()))
n='%.4f'%float(int(math.sqrt(adadlist[i])*10000)/10000)
rishe.append(n)
for x in range(0,len(rishe)):
print(rishe[x])
import math
list = []
n = int(input())
for i in range(n):
digits = float(input())
x = math.sqrt(digits)
formula = '{:.4f}'.format(float(int(x * 10000) / 10000))
list.append(formula)
for v in list:
print(v)
>>> k = 4.35889321
>>> x,y = map(str,str(k).split("."))
>>> print(x+"."+(y[:4]))
4.3588
Here is my code:
E = 2.7182818284590452353602875
n = int(input())
print(round(E,n))
For example, I need to round this to 24 decimal
But it`s gives just:
E = 2.71828182845
#No more
How to fix this?
Do not use Python float for this task because it will lose numbers due to precision. Use decimal module:
from decimal import Decimal
E = Decimal('2.7182818284590452353602875')
n = int(input())
print(E.quantize(Decimal('1.' + '0' * n)))
Output:
2.718281828459045235360288
As ingvar mentions the decimal module is necessary to get this level of precision. That said, you can also let it do the work of generating e in the first place via the exp recipe included in the docs, so you don't have to hardcode a specific value:
from decimal import localcontext, Decimal
def exp(x):
"""Return e raised to the power of x. Result type matches input type.
>>> print(exp(Decimal(1)))
2.718281828459045235360287471
>>> print(exp(Decimal(2)))
7.389056098930650227230427461
>>> print(exp(2.0))
7.38905609893
>>> print(exp(2+0j))
(7.38905609893+0j)
"""
with localcontext() as ctx:
ctx.prec += 2
i, lasts, s, fact, num = 0, 0, 1, 1, 1
while s != lasts:
lasts = s
i += 1
fact *= i
num *= x
s += num / fact
return +s
n = int(input())
with localcontext() as ctx:
ctx.prec = n + 1 # Use exactly the precision needed (one more than requested as 2 counts)
print(exp(Decimal(1)))
which, given an input of 24, outputs:
2.718281828459045235360287
Try it online!
I want to convert decimal float numbers in python into twos complement decimal binary numbers. For example 1.5 in twos complement decimal 2.6 (8 bits) would be 0b011000.
Is there a module that can do this for me?
What you're describing has nothing at all to do with decimal. You want to convert a float to a fixed-point binary representation. To do this, you would multiply the float by a scale factor, cast it to an integer, and use Python's built-in string formatting tools to get the string representation:
def float_to_binary(float_):
# Turns the provided floating-point number into a fixed-point
# binary representation with 2 bits for the integer component and
# 6 bits for the fractional component.
temp = float_ * 2**6 # Scale the number up.
temp = int(temp) # Turn it into an integer.
# If you want -1 to display as 0b11000000, include this part:
# if temp < 0:
# temp += 2**8
# The 0 means "pad the number with zeros".
# The 8 means to pad to a width of 8 characters.
# The b means to use binary.
return '{:08b}'.format(temp)
Well, I couldnt find anything so I wrote some code and tested it.Should work...
def floatToTwosComplementDecimal(intBits,decBits,number):
if decBits == 0:
mx = pow(2,intBits-1) - 1 # maximum number
else:
mx = pow(2,intBits-1) - pow(2,-1*decBits) # maximum number
mn = -1*pow(2,intBits-1) # minimum number
if number > mx:
print "number:" + str(number) + " has been truncated to: " + str(mx)
number = mx
elif number < mn:
print "number:" + str(number) + " has been truncated to: " + str(mn)
number = mn
n = []
m = 0
if number < 0:
n.append(1)
m = -1*pow(2,intBits-1)
else:
n.append(0)
m = 0
for i in reversed(range(intBits-1)):
m1 = m + pow(2,i)
if number < m1:
n.append(0)
else:
n.append(1)
m = m1
for i in range(1,decBits+1):
m1 = m + pow(2,-1*i)
if number < m1:
n.append(0)
else:
n.append(1)
m = m1
return string.join([str(i) for i in n], '')
def twosComplementDecimalToFloat(intBits,decBits,binString):
n = 0.0
if binString[0] == "1":
n = -1*pow(2,intBits-1)
for i in range(intBits-1):
n += int(binString[intBits-1-i])*pow(2,i)
for i in range(1,decBits+1):
n += int(binString[intBits-1+i])*pow(2,-1*i)
return n
You can use the Binary fractions package. This package implements TwosComplement with binary integers and binary fractions. You can convert binary-fraction strings into their twos complement and vice-versa
Example:
>>> from binary_fractions import TwosComplement
>>> str(TwosComplement(-1.5)) # float --> TwosComplement
'10.1'
>>> str(TwosComplement(1.5)) # float --> TwosComplement
'01.1'
>>> TwosComplement.to_float("11111111111") # TwosComplement --> float
-1.0
>>> TwosComplement.to_float("11111111100") # TwosComplement --> float
-4.0
>>> str(TwosComplement(5)) # int --> TwosComplement
'0101'
To use this with Binary's instead of float's you can use the Binary class inside the same package.
PS: Shameless plug, I'm the author of this package.