Question

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.

No correct solution

OTHER TIPS

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 

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top