I want to use "math.sqrt" and my output should have 4 decimal after point even for numbers like "4". is there any func or way?!
I used "round(num_sqrt, 4)" but it didn't work.
my input is like:
1
2
3
19
output must be:
1.0000
1.4142
1.7320
4.3588
and my output is:
1.0
1.4142
1.7320
4.3588
Try this
from decimal import Decimal
import math
# example with sqrt function
y = Decimal(math.sqrt(4))
z = round(y, 4)
print(z) # output 2.0000
# First we take a float and convert it to a decimal
x = Decimal(16.0/7)
print(x)
# Then we round it to 4 places
output = round(x,4)
print(output) # outpun 2.2857
Try this if you really need unnecessary zeros:
def format_floats(reference, values):
formatted_values = []
for i in range(len(values)):
length = len(str(reference)[str(reference).find("."):])-1
new_float = str(round(values[i], length))
new_float += "0"*(len(str(reference))-len(new_float))
formatted_values.append(new_float)
return formatted_values
if __name__ == '__main__':
reference = 0.12345
values = [1.04, 2.045, 2.0]
print(format_floats(reference, values))
output: ['1.04000', '2.04500', '2.00000']
Related
I need to round only the last 2 positives of a float number in Python
EX:
0.000000302329303 -> 0.00000031
0.09838 -> 0.10
0.0003299 -> 0.00033
Is this possible in a simple way like round?
I think your examples are wrong, but just adjust the code as you need:
# this code doesn't work if some are defined as 0.123 and others as .123
a = 0.000000302329303
nb_characters = len(str(a))
rounding_expr = "%%.%sf" % (nb_characters - 4)
rounded_a = float(rounding_expr % a)
One way to do it is to calculate the exponent with log in base 10, and take its negative value:
import math
z = 1
x = 0.09838
rounded_x = round(x, math.ceil(-math.log10(x)) + z)
Now you can change z to set the number of digits
Notice that in general using round might convert the float into scientific representation (mantissa and exponent), so in very small numbers it might be less accurate.
got it this way
from math import ceil, floor
def float_round(num, direction = floor):
zeros = 0
number = num
while number < 0.1:
number *= 10
zeros += 1
places = zeros + 2
return direction(num * (10**places)) / float(10**places)
a = 43.0093
print(float_round(a, ceil)) ## 43.01
a = 0.018552876
print(float_round(a, ceil)) ## 0.019
a = 0.03352
print(float_round(a, ceil)) ## 0.034
a = 0.0998844
print(float_round(a, ceil)) ## 0.1
a = 0.1093
print(float_round(a, ceil)) ## 0.11
a = 33.0093
print(float_round(a, ceil)) ## 33.01
Thanks to everyone, the answer was essential for me to be able to think of something.
I want to use str.format to convert 2 number to scientific notation raised to the same exponential but the exponential need to be set off the str.format.
Example:
from math import log10
y=10000
x=round(np.log10(y))
m=10
y="{:e}".format(y)
m="{:e}".format(m)
print(y)
print(m)
here I have that m has e = 1 and y e = 4 and what I want is for both to have the same "e". i want to set both to exponencial x.
I think you have to calculate this yourself, for example using a helper function which returns a string:
def format_exp(x, n):
significand = x / 10 ** n
exp_sign = '+' if n >= 0 else '-'
return f'{significand:f}e{exp_sign}{n:02d}'
Explanation:
x is the number to format, and n is the power that you want to display;
significand calculates the part to show in front of the e by dividing x by 10n (10 ** n);
exp_sign is either + or -, depending on the value of n (to replicate the default behaviour).
Example usage:
>>> import math
>>> y = 10000
>>> m = 10
>>> x = math.floor(math.log10(y)) # x = 4
>>> print(format_exp(y, x))
1.000000e+04
>>> print(format_exp(m, x))
0.001000e+04
>>> print(format_exp(y, 1))
1000.000000e+01
>>> print(format_exp(m, 1))
1.000000e+01
You can increase the complexity of this function by adding an additional parameter d to set the number of decimals printed in the significand part (with a default value of 6 to reproduce the default Python behaviour):
def format_exp(x, n, d=6):
significand = x / 10 ** n
exp_sign = '+' if n >= 0 else '-'
return f'{significand:.{d}f}e{exp_sign}{n:02d}'
With this function, you can control the number of decimals printed:
>>> print(format_exp(y, x)) # default behaviour still works
1.000000e+04
>>> print(format_exp(y, x, 4))
1.0000e+04
>>> print(format_exp(y, x, 1))
1.0e+04
[Working with Python 3.x]
I'm trying to display 2D line equations. I'm assuming the coefficents or constants to be float because it's possible they can be float. However, if they are integers, I'd like to show them as integers.
That is, instead of
x + 3.0y = 13.0
I want to display
x + 3y = 13
However,
x + 3.5y = 13.5
should stay as is.
How do I do this kind of conditional formatting?
Assumming the function for that will only be passed an exact multiplier (without unknown variable), input and output are strings:
def simplifyFloat(str):
f = float(str)
if f % 1 == 0: #if f has some floating point this is going to be false
f = int(f)
return str(f)
And usage:
equation = '2.0x + 3.5y + 2'
x_part, o, y_part, o, const_part = equation.split(' ') # o variables for dumping operators
# [:-1] before string means you get rid of the last letter, which is 'x' and 'y'
print(simplifyFloat(x_part[:-1])) # output '2'
print(simplifyFloat(y_part)[:-1]) # output '3.5'
There might be more efficient ways to do that, but branching with ceil value works correctly:
import math
number1 = 3.0
number2 = 3.5
def integral_formatting(n):
return n if n != math.ceil(n) else math.ceil(n)
>>> integral_formatting(number1)
3
>>> integral_formatting(number2)
3.5
An efficient way I can come up with, is to make a function that returns integer or float, depending on the case. The function can be like
def check(x):
if int(x) == x:
return int(x)
else:
return float(x)
Now, any number can be put in equation as check(1.0) * x + check(13) * y = check(13.5). This will result in 1x + 13y = 13.5. Hope this helps!
I want to split a decimal number into a random table where the sum of the elements in the array equals the original number
# Call a function which receives a decimal number
from decimal import Decimal
from something import split_random_decimal
split_decimal = split_random_decimal(Decimal('10.00'))
print(split_decimal)
# Output: [1.3, 0.7, 1.2, 0.8, 1.0, 1.5, 0.5, 1.9, 0.1, 1.0]
print(sum(split_decimal))
# Output: Decimal('10.00') - The original decimal value
Has anyone an idea how I could do this in pure Python without using a library?
Solved!
Thks for all who have help me, the final beautiful code who saved my life is this:
import random
def random_by_number(number, min_random, max_random, spaces=1, precision=2):
if spaces <= 0:
return number
random_numbers = [random.uniform(min_random, max_random) for i in range(0, spaces)]
increment_number = (number - sum(random_numbers)) / spaces
return [round(n + increment_number, precision) for n in random_numbers]
number = 2500.50
spaces = 30
max_random = number / spaces
min_random = max_random * 0.6
random_numbers = random_by_number(number, min_random, max_random, spaces=spaces, precision=2)
print(random_numbers)
print(len(random_numbers))
print(sum(random_numbers))
You could start with something like:
numberLeft = 10.0
decList = list()
while numberLeft > 0:
cur = random.uniform(0, numberLeft)
decList.append(cur)
numberLeft -= cur
This implementation would choose higher random numbers at first which wouldn't be that hard to logically change.
numberLeft will never hit exactly 0 so you could do something with rounding. You could also wait for numberLeft to get low enough and that would be your last random number in the list.
The problem is a little under defined: into how many pieces should it be split and how large may any piece be? Should the values only be positive? An approximate solution from what you've said would be to pick a random number of pieces (defaulting to 10) and making the values be distributed normally about the average size of the pieces with a standard deviation of 1/10 of the average:
from decimal import Decimal
def split_random_decimal(x, n=10):
assert n > 0
if n == 1:
return [x]
from random import gauss
mu = float(x)/n
s = mu/10
if '.' in str(x):
p = len(str(x)) - str(x).find('.') - 1
else:
p = 0
rv = [Decimal(str(round(gauss(mu, s), p))) for i in range(n-1)]
rv.append(x - sum(rv))
return rv
>>> splited_decimal = split_random_decimal(Decimal('10.00'))
>>> print(splited_decimal)
[Decimal('0.84'), Decimal('1.08'), Decimal('0.85'), Decimal('1.04'),
Decimal('0.96'), Decimal('1.2'), Decimal('0.9'), Decimal('1.09'),
Decimal('1.08'), Decimal('0.96')]
I think this is what you're looking for:
import random as r
def random_sum_to(n, num_terms = None):
n = n*100
num_terms = (num_terms or r.randint(2, n)) - 1
a = r.sample(range(1, n), num_terms) + [0, n]
list.sort(a)
return [(a[i+1] - a[i])/100.00 for i in range(len(a) - 1)]
print(random_sum_to(20, 3)) # [8.11, 3.21, 8.68] example
print(random_sum_to(20, 5)) # [5.21, 7.57, 0.43, 3.83, 2.96] example
print(random_sum_to(20)) # [1 ,2 ,1 ,4, 4, 2, 2, 1, 3] example
n is the number in which you are summing to, and num_terms is the length of the string you would like as a result. Also if you look at the last example you can see that if you don't want to specify a "num_terms" you don't have to and it will do that for you!
How do I get the numbers after a decimal point?
For example, if I have 5.55, how do i get .55?
5.55 % 1
Keep in mind this won't help you with floating point rounding problems. I.e., you may get:
0.550000000001
Or otherwise a little off the 0.55 you are expecting.
Use modf:
>>> import math
>>> frac, whole = math.modf(2.5)
>>> frac
0.5
>>> whole
2.0
What about:
a = 1.3927278749291
b = a - int(a)
b
>> 0.39272787492910011
Or, using numpy:
import numpy
a = 1.3927278749291
b = a - numpy.fix(a)
Using the decimal module from the standard library, you can retain the original precision and avoid floating point rounding issues:
>>> from decimal import Decimal
>>> Decimal('4.20') % 1
Decimal('0.20')
As kindall notes in the comments, you'll have to convert native floats to strings first.
An easy approach for you:
number_dec = str(number-int(number))[1:]
Try Modulo:
5.55%1 = 0.54999999999999982
To make it work with both positive and negative numbers:
try abs(x)%1. For negative numbers, without with abs, it will go wrong.
5.55 % 1
output 0.5499999999999998
-5.55 % 1
output 0.4500000000000002
import math
orig = 5.55
whole = math.floor(orig) # whole = 5.0
frac = orig - whole # frac = 0.55
similar to the accepted answer, even easier approach using strings would be
def number_after_decimal(number1):
number = str(number1)
if 'e-' in number: # scientific notation
number_dec = format(float(number), '.%df'%(len(number.split(".")[1].split("e-")[0])+int(number.split('e-')[1])))
elif "." in number: # quick check if it is decimal
number_dec = number.split(".")[1]
return number_dec
>>> n=5.55
>>> if "." in str(n):
... print "."+str(n).split(".")[-1]
...
.55
Just using simple operator division '/' and floor division '//' you can easily get the fraction part of any given float.
number = 5.55
result = (number/1) - (number//1)
print(result)
Sometimes trailing zeros matter
In [4]: def split_float(x):
...: '''split float into parts before and after the decimal'''
...: before, after = str(x).split('.')
...: return int(before), (int(after)*10 if len(after)==1 else int(after))
...:
...:
In [5]: split_float(105.10)
Out[5]: (105, 10)
In [6]: split_float(105.01)
Out[6]: (105, 1)
In [7]: split_float(105.12)
Out[7]: (105, 12)
Another example using modf
from math import modf
number = 1.0124584
# [0] decimal, [1] integer
result = modf(number)
print(result[0])
# output = 0124584
print(result[1])
# output = 1
This is a solution I tried:
num = 45.7234
(whole, frac) = (int(num), int(str(num)[(len(str(int(num)))+1):]))
Float numbers are not stored in decimal (base10) format. Have a read through the python documentation on this to satisfy yourself why. Therefore, to get a base10 representation from a float is not advisable.
Now there are tools which allow storage of numeric data in decimal format. Below is an example using the Decimal library.
from decimal import *
x = Decimal('0.341343214124443151466')
str(x)[-2:] == '66' # True
y = 0.341343214124443151466
str(y)[-2:] == '66' # False
Use floor and subtract the result from the original number:
>> import math #gives you floor.
>> t = 5.55 #Give a variable 5.55
>> x = math.floor(t) #floor returns t rounded down to 5..
>> z = t - x #z = 5.55 - 5 = 0.55
Example:
import math
x = 5.55
print((math.floor(x*100)%100))
This is will give you two numbers after the decimal point, 55 from that example. If you need one number you reduce by 10 the above calculations or increase depending on how many numbers you want after the decimal.
import math
x = 1245342664.6
print( (math.floor(x*1000)%1000) //100 )
It definitely worked
Another option would be to use the re module with re.findall or re.search:
import re
def get_decimcal(n: float) -> float:
return float(re.search(r'\.\d+', str(n)).group(0))
def get_decimcal_2(n: float) -> float:
return float(re.findall(r'\.\d+', str(n))[0])
def get_int(n: float) -> int:
return int(n)
print(get_decimcal(5.55))
print(get_decimcal_2(5.55))
print(get_int(5.55))
Output
0.55
0.55
5
If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.
Source
How to get rid of additional floating numbers in python subtraction?
You can use this:
number = 5.55
int(str(number).split('.')[1])
This is only if you want toget the first decimal
print(int(float(input()) * 10) % 10)
Or you can try this
num = float(input())
b = num - int(num)
c = b * 10
print(int(c))
Using math module
speed of this has to be tested
from math import floor
def get_decimal(number):
'''returns number - floor of number'''
return number-floor(number)
Example:
n = 765.126357123
get_decimal(n)
0.12635712300004798
def fractional_part(numerator, denominator):
# Operate with numerator and denominator to
# keep just the fractional part of the quotient
if denominator == 0:
return 0
else:
return (numerator/ denominator)-(numerator // denominator)
print(fractional_part(5, 5)) # Should be 0
print(fractional_part(5, 4)) # Should be 0.25
print(fractional_part(5, 3)) # Should be 0.66...
print(fractional_part(5, 2)) # Should be 0.5
print(fractional_part(5, 0)) # Should be 0
print(fractional_part(0, 5)) # Should be 0
Easier if the input is a string, we can use split()
decimal = input("Input decimal number: ") #123.456
# split 123.456 by dot = ['123', '456']
after_coma = decimal.split('.')[1]
# because only index 1 is taken then '456'
print(after_coma) # '456'
if you want to make a number type
print(int(after_coma)) # 456
a = 12.587
b = float('0.' + str(a).split('.')[-1])
What about:
a = 1.234
b = a - int(a)
length = len(str(a))
round(b, length-2)
Output:
print(b)
0.23399999999999999
round(b, length-2)
0.234
Since the round is sent to a the length of the string of decimals ('0.234'), we can just minus 2 to not count the '0.', and figure out the desired number of decimal points. This should work most times, unless you have lots of decimal places and the rounding error when calculating b interferes with the second parameter of round.
You may want to try this:
your_num = 5.55
n = len(str(int(your_num)))
float('0' + str(your_num)[n:])
It will return 0.55.
number=5.55
decimal=(number-int(number))
decimal_1=round(decimal,2)
print(decimal)
print(decimal_1)
output: 0.55
See what I often do to obtain numbers after the decimal point in python
3:
a=1.22
dec=str(a).split('.')
dec= int(dec[1])
If you are using pandas:
df['decimals'] = df['original_number'].mod(1)