Cube root calculation in python

I am 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 does he always return me 1 ? I am trying to calculate the approximation of the Right and Left integral, and the latter is applicable to the Simpson Rule , but Python does not seem to like this expression. Help? * Full 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 ) 
+7
source share
4 answers

Use floating point math (1/3 truncates to zero). Also, there is no need for math.pow (** for exponentiation) ...

 (1 + math.cos(i)) ** (1 / 3.0) 

In addition, min , max and eval are built-in functions - you will obscure them.

Also, the extra spaces you add to the function call arguments are against PEP-8 (Python Style Guide). In particular, this paragraph:

http://www.python.org/dev/peps/pep-0008/#whitespace-in-expressions-and-statements

+17
source

Using

 1/3.0 

instead

 1/3 

in your code. Otherwise, your score will always be 0 due to integer truncation.

Whether to use ** or math.pow() depends on your preference, most of them probably just use ** .

It is probably not a good idea to define a function called eval , since eval () is already in use by Python as an inline function.

Background:

Note that you can also do 1.0 / 3 or 1.0 / 3.0 .. as long as one of the operands in the section is float , the result will be float .

However, this float(1/3) will not work, as it converts 0 as a result of integer division 1/3 to float , giving you 0.0

In Python 3.x, the split operator / would work as you would expect (i.e., it would give you a float value even with two integer operands). To get integer division, you need to use // .

So, if you were to run this under Python 3.x, you would not run into this particular problem.

+10
source

1/3 is a whole division, rating 0. Try 1./3

0
source

I think this is because you are doing integer arithmetic, where you are really going to do floating point arithmetic. Try changing [second] 1 to 1.0:

 def eval( i ): return math.pow( (1 + math.cos( i )), 1.0/3) 
0
source

All Articles