I'm trying to evaluate the following function in python:
f(x) = (1 + cos(x))^(1/3)
def eval( i ):
return math.pow( (1 + math.cos( i )), 1/3)
why is it always returning me 1?
I'm trying to calculate the Right and Left approximation of an integral, and latter apply Simpson's Rule, but Python does not seem to like that expression.
Help?
*Complete Code *
import math
min = 0
max = math.pi / 2
n = 4
delta = ( min + max ) / n
def eval( i ):
return math.pow( (1 + math.cos( i )), 1/3)
def right( ):
R = 0
for i in range(1, n+1):
R += eval( i )
return R
def left():
L = 0
for i in range(0, n):
print eval( i )
L += eval( i )
Python Get Cube Root Using the Exponent Symbol ** For example, the cube root of integer -27 should be -3 but Python returns 1.5000000000000004+2.598076211353316j .
sqrt() function is an inbuilt function in Python programming language that returns the square root of any number. Syntax: math. sqrt(x) Parameter: x is any number such that x>=0 Returns: It returns the square root of the number passed in the parameter.
Use floating point math (1 / 3 truncates to zero). Also, no need for math.pow (** for exponentiation)...
(1 + math.cos(i)) ** (1 / 3.0)
Also, min, max and eval are built-in functions - you are shadowing them.
Also, the extra spaces you are adding in your function call arguments are against PEP-8 (Python Style Guide). Specifically this paragraph:
http://www.python.org/dev/peps/pep-0008/#whitespace-in-expressions-and-statements
Use
1/3.0
instead of
1/3
in your code. Otherwise your exponent will always be 0 due to integer truncation.
Whether to use ** or math.pow() is up to your preference, most would probably just use **.
It's probably not a good idea to define a function named eval since eval() is already in use by Python as a built-in function.
Background:
Note that you could also do 1.0 / 3 or 1.0 / 3.0 .. as long as one of the operands in the division is a float the result will be a float.
However, this float(1/3) would not work since it would convert the 0 resulting from the integer division 1/3 into a float giving you 0.0
Under Python 3.x the division operator / would have worked as you expected (ie it would give you a float value even with two integer operands). To get integer division you would have to use //.
So had you run this under Python 3.x you would not have encountered this particular problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With