Calculating exp(x) with the use of recursion in Python [duplicate] - python

This question already has answers here:
Why does the division get rounded to an integer? [duplicate]
(13 answers)
Closed 7 years ago.
I'm attempting to calculate e^x using recursion, e^x = e^(x/2)*e^(x/2), and the third order Maclaurin expansion for e^x and the script keeps returning 1. I'm not looking for a higher accuracy solution, just simply to understand where the script goes wrong : )
My thought is that with enough iterations it should end up with (1+x/N+(x/N)^2/2)^N when the function value goes below the limit.
def exp(x):
if abs(x)<0.0001:
return 1+x+x**2/2
else:
y=exp(x/2)
return y*y

Try this instead (note the 2.0 in the recursive call):
def exp(x):
if abs(x) < 0.0001:
return 1 + x + x**2 / 2.0
else:
y = exp(x / 2.0)
return y * y
It is failing because if you pass an integer in for x, say 1, then x / 2 does integer division (in python 2.x), which would result in 0 instead of 0.5. By using x / 2.0, it forces python to use float division.

def exp(x):
if abs(x)<0.0001:
return 1+x+(x**2)/2.0
else:
y=exp(x/2.0)
return y*y
Integer division truncates. You need floats here.

Related

Write Numeric Manipulation in Python in 1 line [duplicate]

This question already has answers here:
How can I clamp (clip, restrict) a number to some range?
(9 answers)
Closed 4 years ago.
i have a simple problem in Python where i need to return a value that is equal to floor if it is smaller than floor, and return ceiling if the value is larger than ceiling. I'm not sure if there is a simpler way to do so. What i will do is:
def floor_ceil(x):
floor = 0
ceil = 100
if x < floor:
return floor
elif x > ceil:
return ceil
return x
Are there simpler ways to do so? The code looks clunky
You could reuse the built-in max and min:
def floor_ceil(x):
return max(0, min(100, x))

Division in python2.7 does not produce decimal values [duplicate]

This question already has answers here:
How can I force division to be floating point? Division keeps rounding down to 0?
(11 answers)
What is the difference between '/' and '//' when used for division?
(16 answers)
Closed 5 years ago.
Here is my project on a small scale. The purpose is to approximate pi. I know it isn't neat, but the algorithm is correct.
adds = 0
subtracts = 0
for x in range(0, 10):
adds += 1/(1 + 4*x)
subtracts += 1/(3 + 4*x)
print(adds) #DEBUGGING
print(subtracts) #DEBUGGING
pi = float(4*(adds + subtracts)
print(pi)
Seems like it should work, right? On python 3, the same exact code gives me an accurate answer. However, in 2.7.10, this happens in the shell:
===================== RESTART: C:/Python27/Scripts/pi.py
=====================
1
0
1
0
1
0
1
0
1
0
1
0
1
0
1
0
1
0
1
0
4.0
>>>
Can someone explain to me why this happens and how I can correct this? I have tried conventional methods like converting to strings, formatting, rounding, etc. but none of them work. It is like my variables are being saved as 1's and 0's despite their values constantly changing. Once again, the same code works fine on Python 3.
On python2, division between integers results in integer division with the final answer truncated to a whole number.
>>> 1 / 2
0
On python3, this is not the case, because division automatically results in a float result unless you use the // integer division operator explicitly.
You'll want to have at least one of the operands of float type:
>>> 1. / 2
0.5
for x in range(0, 10):
adds += 1. / (1 + 4 * x)
subtracts += 1. / (3 + 4 * x)
Note the 1. is 1.0.
On Python 2.7, x / y is integer division, but you can use Python 3's real division using __future__ division :
from __future__ import division
adds = 0
subtracts = 0
for x in range(0, 10):
adds += 1/(1 + 4*x)
subtracts += 1/(3 + 4*x)
print(adds) #DEBUGGING
print(subtracts) #DEBUGGING
pi = float(4*(adds + subtracts))
print(pi)
Out :
1.0
0.333333333333
1.2
0.47619047619
1.31111111111
0.5670995671
1.38803418803
0.633766233766
1.44685771745
0.686397812714
1.49447676507
0.729876073583
1.53447676507
0.76691311062
1.56895952369
0.799171175136
1.59926255399
0.827742603708
1.62628958102
0.853383629349
9.91869284146

math.cos function returning different value than calculator [duplicate]

This question already has answers here:
How can I force division to be floating point? Division keeps rounding down to 0?
(11 answers)
Closed 6 years ago.
I have this function that takes in an x value and returns an output y value.
def function(x):
y = math.cos(x**2/2)/(math.log(x+2,2))
return y
When I call the function, I get:
print function(1)
>> 0.630929753571
But WolframAlpha has the value at x = 1 to be 0.553693
Which is the correct value?
This is because you are using Python 2, where the / operator does integer division. This would give you the correct answer in Python 3:
>>> def f(x):
... y = math.cos(x**2/2)/(math.log(x+2,2))
... return y
...
>>> f(1)
0.5536929495121011
In Python 3, using the // operator, does floor division:
>>> def f(x):
... y = math.cos(x**2//2)/(math.log(x+2,2))
... return y
...
>>> f(1)
0.6309297535714574
>>>
In Python 2, use y = math.cos(x**2/ 2.0) / (math.log(x+2,2))
you are dividing an int by another int which is greater: 1 / 2 and therefore getting the cosine of zero since python 2.7 does not evaluate integer divisions as floating point. Try:
def function(x):
y = math.cos(x ** 2 / 2.0) / (math.log(x + 2, 2))
return y
Python 2 division operator does integer division, unless you tell it it's a float.
If you change to x**2/2.0 you will get the correct answer, like wolfram alfa.
Python 2 rounds to integer when you divide integer by integer so use one float number (i.e 2.0) when you divide to get correct result
import math
def function(x):
y = math.cos(x**2/2.0)/(math.log(x+2,2))
return y
print function(1)

Modulo operator in Python [duplicate]

This question already has answers here:
How does the modulo (%) operator work on negative numbers in Python?
(12 answers)
Closed last month.
What does modulo in the following piece of code do?
from math import *
3.14 % 2 * pi
How do we calculate modulo on a floating point number?
When you have the expression:
a % b = c
It really means there exists an integer n that makes c as small as possible, but non-negative.
a - n*b = c
By hand, you can just subtract 2 (or add 2 if your number is negative) over and over until the end result is the smallest positive number possible:
3.14 % 2
= 3.14 - 1 * 2
= 1.14
Also, 3.14 % 2 * pi is interpreted as (3.14 % 2) * pi. I'm not sure if you meant to write 3.14 % (2 * pi) (in either case, the algorithm is the same. Just subtract/add until the number is as small as possible).
In addition to the other answers, the fmod documentation has some interesting things to say on the subject:
math.fmod(x, y)
Return fmod(x, y), as defined by the platform C
library. Note that the Python expression x % y may not return the same
result. The intent of the C standard is that fmod(x, y) be exactly
(mathematically; to infinite precision) equal to x - n*y for some
integer n such that the result has the same sign as x and magnitude
less than abs(y). Python’s x % y returns a result with the sign of y
instead, and may not be exactly computable for float arguments. For
example, fmod(-1e-100, 1e100) is -1e-100, but the result of Python’s
-1e-100 % 1e100 is 1e100-1e-100, which cannot be represented exactly as a float, and rounds to the surprising 1e100. For this reason,
function fmod() is generally preferred when working with floats, while
Python’s x % y is preferred when working with integers.
Same thing you'd expect from normal modulo .. e.g. 7 % 4 = 3, 7.3 % 4.0 = 3.3
Beware of floating point accuracy issues.
same as a normal modulo 3.14 % 6.28 = 3.14, just like 3.14%4 =3.14 3.14%2 = 1.14 (the remainder...)
you should use fmod(a,b)
While abs(x%y) < abs(y) is true mathematically, for floats it may not be true numerically due to roundoff.
For example, and assuming a platform on which a Python float is an IEEE 754 double-precision number, in order that -1e-100 % 1e100 have the same sign as 1e100, the computed result is -1e-100 + 1e100, which is numerically exactly equal to 1e100.
Function fmod() in the math module returns a result whose sign matches the sign of the first argument instead, and so returns -1e-100 in this case. Which approach is more appropriate depends on the application.
where x = a%b is used for integer modulo

calculating cubic root in python

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 )
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.
New in Python 3.11
The math module now includes a built-in cbrt for cube roots, so your function can be implemented as:
def f(x):
return math.cbrt(1 + math.cos(x))
The 1/3 is an integer divide, evaluating to 0. Try 1./3
I think it's because you're performing integer arithmetic where you really intend to perform floating-point arithmetic. Try changing the [second] 1 to 1.0:
def eval( i ):
return math.pow( (1 + math.cos( i )), 1.0/3)

Categories

Resources