Suppose if the value is >.5 it will return 1 but if it's<.5 it'll return 0. Is there any built in method in python to do this?I want to use this in machine learning. If possible please give me a sample
numpy has a round function that will round to nearest floating point, which you could use. Or just make your own. Something like this should work for numbers between [0.0, 1.0] and return integers:
>>> def rnd(x):
... return int(x + 0.5)
...
>>> rnd(0.4)
0
>>> rnd(0.6)
1
>>> rnd(0.5)
1
You can use the round() function in Python.
print(round(31.5)) gives 32 and
print(round(31.4)) gives 31.
Does this answer your query?
Related
In math, you are allowed to take cubic roots of negative numbers, because a negative number multiplied by two other negative numbers results in a negative number. Raising something to a fractional power 1/n is the same as taking the nth root of it. Therefore, the cubic root of -27, or (-27)**(1.0/3.0) comes out to -3.
But in Python 2, when I type in (-27)**(1.0/3.0), it gives me an error:
Traceback (most recent call last):
File "python", line 1, in <module>
ValueError: negative number cannot be raised to a fractional power
Python 3 doesn't produce an exception, but it gives a complex number that doesn't look anything like -3:
>>> (-27)**(1.0/3.0)
(1.5000000000000004+2.598076211353316j)
Why don't I get the result that makes mathematical sense? And is there a workaround for this?
-27 has a real cube root (and two non-real cube roots), but (-27)**(1.0/3.0) does not mean "take the real cube root of -27".
First, 1.0/3.0 doesn't evaluate to exactly one third, due to the limits of floating-point representation. It evaluates to exactly
0.333333333333333314829616256247390992939472198486328125
though by default, Python won't print the exact value.
Second, ** is not a root-finding operation, whether real roots or principal roots or some other choice. It is the exponentiation operator. General exponentiation of negative numbers to arbitrary real powers is messy, and the usual definitions don't match with real nth roots; for example, the usual definition of (-27)^(1/3) would give you the principal root, a complex number, not -3.
Python 2 decides that it's probably better to raise an error for stuff like this unless you make your intentions explicit, for example by exponentiating the absolute value and then applying the sign:
def real_nth_root(x, n):
# approximate
# if n is even, x must be non-negative, and we'll pick the non-negative root.
if n % 2 == 0 and x < 0:
raise ValueError("No real root.")
return (abs(x) ** (1.0/n)) * (-1 if x < 0 else 1)
or by using complex exp and log to take the principal root:
import cmath
def principal_nth_root(x, n):
# still approximate
return cmath.exp(cmath.log(x)/n)
or by just casting to complex for complex exponentiation (equivalent to the exp-log thing up to rounding error):
>>> complex(-27)**(1.0/3.0)
(1.5000000000000004+2.598076211353316j)
Python 3 uses complex exponentiation for negative-number-to-noninteger, which gives the principal nth root for y == 1.0/n:
>>> (-27)**(1/3) # Python 3
(1.5000000000000004+2.598076211353316j)
The type coercion rules documented by builtin pow apply here, since you're using a float for the exponent.
Just make sure that either the base or the exponent is a complex instance and it works:
>>> (-27+0j)**(1.0/3.0)
(1.5000000000000004+2.598076211353316j)
>>> (-27)**(complex(1.0/3.0))
(1.5000000000000004+2.598076211353316j)
To find all three roots, consider numpy:
>>> import numpy as np
>>> np.roots([1, 0, 0, 27])
array([-3.0+0.j , 1.5+2.59807621j, 1.5-2.59807621j])
The list [1, 0, 0, 27] here refers to the coefficients of the equation 1x³ + 0x² + 0x + 27.
I do not think Python, or your version of it, supports this function. I pasted the same equation into my Python interpreter, (IDLE) and it solved it, with no errors. I am using Python 3.2.
How can I round this number 838062.5 to 838063 instead of to 838062, using the round() function in Python?
Use math.ceil to round up:
import math
print(math.ceil(838062.5)) # prints 838063
The Python documentation for the round() function explains this interesting phenomenon:
If two multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2).
While you could use floor and ceiling operations, matching the various cases may be a pain. So, I recommend using the decimal module, which allows you to always round half-values up.
>>> import decimal
>>> decimal.getcontext().rounding = decimal.ROUND_HALF_UP
>>> n = decimal.Decimal(838062.5)
>>> n
Decimal('838062.5')
>>> round(n)
838062
All I had to do was add 0.5 and take the floor value:
import math
x = 838062.5 + 0.5
print(math.floor(x))
I am using Python to model the statistical physical, so I will deal with small numbers.
For example,
a = 2.22e-300, b = 3e-200
and I want to calculate
a * b = 6.66e-500.
However, in Python 3 it shows 0.0.
I am thinking to design a data type: the first part to store the float number, which is 6.66 here, and the second part stores the magnitude, which is -500.
May I ask how I can implement this? Or is there any better way to deal with the scientific number?
Create a class:
class Sci_note:
def __init__(self, base, exp):
self.base = base
self.exp = exp
def __mul__(self, other):
return Sci_note(self.base * other.base,
self.exp + other.exp)
def __str__(self):
return str(self.base) + 'e' + str(self.exp)
and it functions as you would expect:
>>> a = Sci_note(2.22, -300)
>>> b = Sci_note(3, -200)
>>> c = a * b
>>> c.base
6.66
>>> c.exp
-500
update
I added a __str__ method (above), so they are displayed properly when printed:
>>> print(a)
2.22e-300
Of course, I have only implemented the multiplication method here, but I will leave it up to you to implement the others when required. It may be the case that you only need multiplication so I would be wasting everyone's time if I wrote them now!
In addition, creating a __float__ handler would also not be useful here, as Python can't handle floats of the order ^-300, so it would be useless to return them as we would just get 0!
I strongly suggest you use something like the built-in decimal module and increase its precision to your needs. For example:
>>> from decimal import *
>>> getcontext().prec = 100
>>> a = Decimal("2.22e-300")
>>> b = Decimal("3e-200")
>>> a
Decimal('2.22E-300')
>>> b
Decimal('3E-200')
>>> a*b
Decimal('6.66E-500')
Note that, to be on the safe side, I create a and b using strings such as "3e-200" to let the decimal module parse them correctly. If not, it will first convert them to Python's inexact floating points and muck them up before passing them into Decimal objects.
In the above code, we set the precision to 100.
How do I make the decimal in Python more accurate, so that I can calculate up to
0.0000000000001 * 0.0000000000000000001 = ?
I need to add decimals like 0.0000000145 and 0.00000000000000012314 and also multiply them and get the exact result. Is there a needed code, or is there a module? Thanks in advance.
I need something that is more accurate than decimal.Decimal.
Not sure why you're getting downvoted.
decimal.Decimal represents numbers using floating point in base 10. Since it isn't implemented directly in hardware, you can control the level of precision (which defaults to 28 places):
>>> from decimal import *
>>> getcontext().prec = 6
>>> Decimal(1) / Decimal(7)
0.142857
However, you may prefer to use the mpmath module instead, which supports arbitrary precision real and complex floating point calculations:
>>> from mpmath import mp
>>> mp.dps = 50
>>> print(mp.quad(lambda x: mp.exp(-x**2), [-mp.inf, mp.inf]) ** 2)
3.1415926535897932384626433832795028841971693993751
Maybe do something like
format(0.0000000000001 * 0.0000000000000000001,'.40f')
The '.40f' could be changed to get more accuracy!
eg.: '.70f' or something like that.
Here 70 implies I want 70 digits of accuracy.
I want to avoid my code mistaking a near integer for an integer. For example, 58106601358565889 has as its square root 241,053,109.00000001659385359763188, but when I used the following boolean test, 58106601358565889 fooled me into thinking it was a perfect square:
a = 58106601358565889
b = math.sqrt(a)
print(b == int(b))
The precision isn't necessarily the problem, because if I re-check, I get the proper (False) conclusion:
print(a == b**2)
What would be a better way to test for a true versus a near integer? The math.sqrt is buried in another definition in my code, and I would like to avoid having to insert a check of a squared square root, if possible. I apologize if this is not a good question; I'm new to python.
import numpy as np
import math
from decimal import *
a = 58106601358565889
b = np.sqrt(a)
c = math.sqrt(a)
d = Decimal(58106601358565889).sqrt()
print(d)
print(int(d))
print(c)
print(int(c))
print(b)
print(int(b))
o/p
241053109.0000000165938535976
241053109
241053109.0
241053109
241053109.0
241053109
I would say use decimal.
Expected code :
from decimal import *
d = Decimal(58106601358565889).sqrt()
print(d == int(d))
o/p
False
This isn't a matter of distinguishing integers from non-integers, because b really is an integer*. The precision of a Python float isn't enough to represent the square root of a to enough digits to get any of its fractional component. The second check you did:
print(a == b**2)
only prints False because while b is an integer, b**2 still isn't a.
If you want to test whether very large integers are exact squares, consider implementing a square root algorithm yourself.
*as in 0 fractional part, not as in isinstance(b, int).
It's not the precision of the int that is the problem - it's the limited precision of floats
>>> import math
>>> math.sqrt(58106601358565889)
241053109.0
>>> math.sqrt(58106601358565889) - 241053109
0.0
I think the double check would be the obvious solution
You could also look at the gmpy2 library. It has a function for calculating the integer square root and also the integer square root plus remainder. There are no precision constraints.
>>> import gmpy2
>>> gmpy2.isqrt(58106601358565889)
mpz(241053109)
>>> gmpy2.isqrt_rem(58106601358565889)
(mpz(241053109), mpz(8))
>>>
Disclaimer: I maintain gmpy2.