1

I wrote a crule1.py as follows.

 def exp_rule1 (mu1, h, alpha): return h**2/(4*mu1**2) 

Then I run it in the Interpreter. I got

Python 2.7.6 |Anaconda 1.9.1 (64-bit)| (default, Nov 11 2013, 10:49:15) [MSC v.1500 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. Imported NumPy 1.8.0, SciPy 0.13.3, Matplotlib 1.3.1 Type "scientific" for more details. >>> import crul1 as c1 >>> c1.exp_rule1(1, 1, 0) 0 

Then I copy the code into interpreter. The result is

>>> def exp_rule1 (mu1, h, alpha): ... return h**2/(4*mu1**2) ... >>> exp_rule1(1, 1, 0) 0.25 

It makes me very confused and I cannot fix it. You are very appreciated to point out the problem in this code.

3
  • 2
    both instances running python 2? Commented Mar 4, 2014 at 19:01
  • Define "interpreter". Are you running the second in the same shell as the import cru1 as c1, c1.exp_rule1(1, 1, 0) lines? Commented Mar 4, 2014 at 19:03
  • Yes, I run the same shell. The version is Python 2.7 Commented Mar 6, 2014 at 20:39

2 Answers 2

2

In Python 2.x, / returns an integer value if both its operands are integers. As a special case, n/d is 0 if n < d and both are positive.

For

def exp_rule1 (mu1, h, alpha): return h**2/(4*mu1**2) 

you want to ensure that either the numerator or denominator is a floating point value. A simple way to do that is to make the 4 a float instead of an integer.

def exp_rule1 (mu1, h, alpha): return h**2/(4.0*mu1**2) 

Another solution is to import the new 3.x behavior for /, which is to always return a float regardless of the operands. If you do this, replace any divisions where you rely on integer division with // instead.

# This allows 1/2 to return 0.5 instead of 0 from __future__ import division 
Sign up to request clarification or add additional context in comments.

Comments

0

The problem is you're mixing integers and floats. Try making the call exp_rule1(1.0, 1.0, 0.0) and you'll get the right result. Just make sure all the arguments to the function are floats.

2 Comments

But both cases appear to mix integers and floats in the same way, don't they?
Specifically, you are doing integer division instead of float division. 1/2 is zero for ints, .5 for floats.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.