Python Convert Decimal Fixed Point List to Radians - python

I have a list of decimal fixed point numbers:
latitude = Places.query.with_entities(Places.latitude).all()
result = []
for i in range(len(latitude)):
result.append(latitude[i][0])
print result
The output of latitude is this
I wanted to map them to Radians. So, I did this:
lat_ = map(lambda i: radians(i), result)
But got an errorTypeError: a float is required
I want to know what is the correct way to do this operation. `
Edit
Now the result looks like this:
[28.633, 29.333,...]
And error is:
TypeError: float() argument must be a string or a number

Try this:
rads = [x['latitude'] for x in result]
_lat = map(lambda i: radians(i), rads)

The problem is that the radians function from the maths module expects an input of type float, not of type Decimal. You'll have to convert the values to float first:
lat_ = map(lambda i: radians(float(i)), result)

from decimal import *
from math import radians
result = [Decimal('77.216700'), Decimal('77.250000'), Decimal('77.216700'), Decimal('77.216700'), Decimal('77.200000'), Decimal('77.216700')]
lat_ = map(lambda i: radians(float(i)), result)
# [1.3476856525247056, 1.3482668471656196, 1.3476856525247056,
# 1.3476856525247056, 1.3473941825396225, 1.3476856525247056]

Related

Convert a float in scientific notation to a "d.dd x 10^(-n)"

I'm building a calculator to calculate some chemistry related calculations. So most of the results will be extremely small values.
An example result is 4.840909814726882e-09.
How do I display this value in a format like 4.84 x 10^(-9)?
try this:
format(4.840909814726882e-09, '.2e').replace('e', ' x 10^(') + ')'
Output:
4.84 x 10^(-09)
It's not exactly the result you wanted but it's simple.
Also there is:
def my_format(num):
s = format(num, '.2e')
base, exp = s.split('e')
return f'{base} x 10^({int(exp)})'
Output:
>>> my_format(4.840909814726882e-09)
'4.84 x 10^(-9)'
which is more coplicated but it's exectly the result you wanted.
How do I display the value to a format like 4.84 x 10^(-9) ?
By hand, that is not a format supported by Python.
Although if you just want to "round off" the number because you neither have nor need 15 significant digits, then you can use format specifiers, and either the g presentation type:
>>> format(v, 'g')
'4.84091e-09'
or an explicit precision:
>>> format(v, '.3')
'4.84e-09'

How to format float to integer if the value is integral. That is, display 13.0 as 13 but 13.5 as 13.5

[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!

How to get rid of additional floating numbers in python subtraction?

def function():
n=123.456
x=int(n)
y=n-int(n)
print(x,y)
result:
x= 123
y= 0.45600000000000307
how to get exactly .456 without using library function,
n can be any floating number
If you know from the outset that the number of decimal places is 3, then:
y = round(n - int(n), 3)
If you don't know the number of decimal places, then you can work it out, as so:
y = round(n - int(n), str(n)[::-1].find('.'))
As furas pointed out, you can also use the decimal package:
from decimal import Decimal
n = Decimal('123.456')
y = n - int(n)
You can also use the re module:
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(123.456))
print(get_decimcal_2(123.456))
print(get_int(123.456))
Output
0.456
0.456
123
You can use %f to round of the floating value to required digits.
def function(n):
x = int(n)
y = n-int(n)
print(x,"%.2f" % y)
function(123.456)
Output:
123
0.456
Try with round(y,n), and n=3 its the numbers of decimals.

The converted floating to decimal point?

In case
x = 0.898558 #float with zero prefix
I tried
from decimal import Decimal
x = 0.898558
print(Decimal(x))
Output:
0.898557999999999967855046634213067591190338134765625
I think i can do something and i tried
x = 0.898558
print('%.2f' % x)
Ouput:
0.89
How i can remove the 0 digit,i want something like this 89
You could do this by converting your int to a string and splitting by the decimal point.
x = str(x).split('.')[1]
Its just a string, so you can slice off the bit you want:
print( ('%.2f' % x)[2:] )
Multiply by 100, then convert to int:
y = int(x*100)
EDIT: This is WRONG. See discussion in the comments.

How to get numbers after decimal point?

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)

Categories

Resources