Why is "(1/6)*(66.900009-62.852596)" evaluating to zero? - python

Tried in both Objective-C (Xcode) and Python (terminal) and (1/6)*(66.900009-62.852596) evaluates to zero both times. Anyone know why this is? Shouldn't it be 0.26246?

You are doing integer arithmetic on 1/6, and the floor of 1/6 is 0. Try 1.0/6 instead.

1/6 is integer division, which becomes 0. Try using 1.0/6 instead.

The avoid doing accidental floor division with integer imports, do a from __future__ import division at the top of your module:
>>> from __future__ import division
>>> (1/6)*(66.900009-62.852596)
0.6745688333333331
The future module is responsible for enabling features that will be turned out by default in Python 3.

Related

Why python and python3 are giving different arithmetic results? [duplicate]

Consider this division in Python 3:
>>> 2/2
1.0
Is this intended? I strongly remember earlier versions returning int/int = int. What should I do? Is there a new division operator or must I always cast?
In 2.x, the behaviour was indeed reversed; see How can I force division to be floating point? Division keeps rounding down to 0? for the opposite, 2.x-specific problem.
Take a look at PEP-238: Changing the Division Operator
The // operator will be available to request floor division unambiguously.
Oops, immediately found 2//2. This will output an int rather than a float.
Behavior of the division operator in Python 2.7 and Python 3
In Python 2.7: By default, division operator will return integer output.
To get the result in double, multiply the dividend or divisor by 1.0.
100/35 => 2 # Expected is 2.857142857142857
(100*1.0)/35 => 2.857142857142857
100/(35*1.0) => 2.857142857142857
In Python 3
// => used for integer output
/ => used for double output
100/35 => 2.857142857142857
100//35 => 2
100.//35 => 2.0 # Floating-point result if the divisor or dividend is real
The accepted answer already mentions PEP 238. I just want to add a quick look behind the scenes for those interested in what's going on without reading the whole PEP.
Python maps operators like +, -, * and / to special functions, such that e.g. a + b is equivalent to
a.__add__(b)
Regarding division in Python 2, there is by default only / which maps to __div__ and the result is dependent on the input types (e.g. int, float).
Python 2.2 introduced the __future__ feature division, which changed the division semantics the following way (TL;DR of PEP 238):
/ maps to __truediv__ which must "return a reasonable approximation of
the mathematical result of the division" (quote from PEP 238)
// maps to __floordiv__, which should return the floored result of /
With Python 3.0, the changes of PEP 238 became the default behaviour and there is no more special method __div__ in Python's object model.
If you want to use the same code in Python 2 and Python 3 use
from __future__ import division
and stick to the PEP 238 semantics of / and //.

Difference between **(1/2), math.sqrt and cmath.sqrt?

What is the difference between x**(1/2) , math.sqrt() and cmath.sqrt()?
Why does cmath.sqrt() get complex roots of a quadratic right alone? Should I use that for my square roots exclusively? What do they do in the background differently?
If you look at the documentation for cmath and math respectively, you will find that:
cmath "provides access to mathematical functions for complex numbers"
math "functions cannot be used with complex numbers; use the functions of the same name from the cmath module if you require support for complex numbers."
The (**) operator maps to the pow function, with the important difference that pow converts its arguments to float.
Hence, you may see different results with the three functions for same arguments, as demonstrated here. Please note that if the expression has a real solution, there will be no difference between the value returned by math.sqrt and the real part of the value returned by cmath.sqrt. However, you will get an error with math.sqrt if no real solution is available.
Edit: As #jermenkoo points out, there will be a difference in the value returned by (**) between Python 2 and 3 due to the difference in how the / operator works. However, if you directly use 0.5 instead of 1/2, that should not cause issues.
As an addition to the existing answers, one notable difference is when processing negative numbers:
>>> import math
>>> math.sqrt(-4)
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
ValueError: math domain error
The sqrt function only works on positive values.
>>> (-4)**0.5
(1.2246467991473532e-16+2j)
The ** operator is able to return a complex number in that case (note the wierd rounding error where the real part should be zero)
import cmath
>>> cmath.sqrt(-4)
2j
cmath.sqrt returns the perfect complex value probably because, as opposed to **, sqrt is a specialized square root computation, not just a float pow function.
** .5 and math.sqrt are going to be nearly identical.
** .5 is going to dispatch you to pow from the standard C library powhttps://hg.python.org/cpython/file/661195a92131/Objects/floatobject.c#l783 and math.sqrt will dispatch you to sqrt in the standard C library sqrt, both of which should have similar performance. A bigger difference would probably be caused by the difference between
from math import sqrt
sqrt(x)
vs
import math
math.sqrt(x)
just because of the lookup of sqrt in the math module.
cmath is different and will be slower. It is for math on complex numbers, which is why it's returning complex numbers. Note that difference between cmath and math is different than packages like cPickle and pickle.

Modulo in sage returning a negative value

I am new to SAGE and am having a problem with something very simple. I have the following code:
delay = float(3.5)
D = delay%1.0
D
But this returns the value -0.5 instead of the expected 0.5. What am I doing wrong?
If I change delay to be delay = float(2.5), I get the right answer, so I don't know why it isn't consistent (I am sure I am using the modulo wrong somehow).
I think that this question will answer things very well indeed for you.
However, I don't know why you are using float in Sage. Then you could just use Python straight up. Anyway, the % operator is tricky to use outside of integers. For example, here is the docstring for its use on Sage rational numbers.
Return the remainder of division of self by other, where other is
coerced to an integer
INPUT:
* ``other`` - object that coerces to an integer.
OUTPUT: integer
EXAMPLES:
sage: (-4/17).__mod__(3/1)
1
I assume this is considered to be a feature, not a bug.

Python Math module subtleties

I've been experimenting with the standard python math module and have come across some subtle difficulties. For example, I'm noticing the following behavior concerning indeterminate forms:
0**0
>>> 1
def inf():
return 1e900
# Will return inf
inf()**inf()
>>> inf
And other anomalies of the sort. I'm writing a calculator, and I'd like to have it be mathematically accurate. Is there something I can do about this? Or, is there some way to circumvent this? Thanks in advance.
There's nothing wrong with your first example. 0**0 is often defined to be 1.
The second example is all to do with precision of doubles. 1E900 exceeds the maximum positive value of a (most likely 64-bit) double. If you want doubles outside of that range, you'll have to look into libraries. Fortunately Python has one built-in: the decimal module.
For example:
from decimal import Decimal
d = Decimal('1E900')
f = d + d
print(f)
>>> 2E900
According to Wolfram (quoting Knuth) while 0**0 is indeterminate, it's sometimes given as 1. This is because holding the statement 'x**0 = 1' to be true in all cases is in some cases useful. Even more interestingly Python will consider NaN**0 to be 1 as well.
http://mathworld.wolfram.com/Power.html
In the case of infinity**infinity, you're not really dealing with the mathematical concept of infinity here (where that would be undefined), but rather a number that's too large and has overflowed. As such all that statement is saying is that a number that's huge to the power of another number that's huge is still a number that's huge.
Edit: I do not think it is possible to overload a built in type (such as float) in Python so overloading the float.__pow__(x,y) operator directly. What you could possibly do is define your own version of float.
class myfloat(float):
def __pow__(x,y):
if(x==y==0):
return 'NaN'
else:
return float.__pow__(x,y)
m = myfloat(0)
m**0
Not sure if that's exactly what you're looking for though.
Well returning NaN for 0**0 is almost always useless and lots of algorithms avoid special cases if we assume 0**0 == 1. So while it may not be mathematically perfect - we're talking about IEEE-754 here, mathematical exactness is really the least of our problems [1]
But if you want to change it, that's rather simple. The following works as expected in Python 3.2:
def my_pow(x, y):
if y == 0: return 'NaN'
return float.__pow__(float(x), y)
pow = my_pow
[1] The following code can theoretically execute the if branch with x86 CPUs (well at least in C and co):
float x = sqrt(y);
if (x != sqrt(y)) printf("Surprise, surprise!\n");

Get ZeroDivisionError: float division in python

In the code below: highly simplified. I get ZeroDivisionError: float division
Any value below one gives errors. Other times 5/365 gives the error.
How do I fix?
import math
def top( t):
return ((.3 / 2) * t) / (.3 * math.sqrt(t))
t = 365/365
top= top(t)
print (top)
The problem is here:
t = 365/365
You are dividing two integers, so python is using integer division. In integer division, the quotient is rounded down. For example, 364/365 would be equal to 0. (365/365 works because it is equal to 1, which is still 1 rounded down.)
Instead, use float division, like so.
t = 365.0/365.0
In addition to cheeken's answer, you can put the following at the top of your modules:
from __future__ import division
Doing so will make the division operator work the way you want it to i.e always perform a (close approximation of) true mathematical division. The default behaviour of the division operator (where it performs truncating integer division if the arguments happen to be bound to integers) was inherited from C, but it was eventually realised that it was not a great fit for a dynamically typed language like Python. In Python 3, this no longer happens.
In my Python 2 modules, I almost always import division from __future__, so that I can't get caught out by accidentally passing integers to a division operation I don't expect to truncate.
It's worth noting that from __future__ import ... statements have to be the very first thing in your module (I think you can have comments and a docstring before it, nothing else). It's not really a normal import statement, even though it looks like one; it actually changes the way the Python interpreter reads your code, so it can't wait until runtime to be exectuted like a normal import statement. Also remember that import __future__ does not have any of the magic effects of from __future__ import ....
Try this:
exponent = math.exp(-(math.pow(x-mean,2)/(2*math.pow(stdev,2))))
A ZeroDivisionError is encountered when you try to divide by zero.

Categories

Resources