Python: Derivative of trig functions [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I am trying to identify what the problem with the differentiation of trig functions in Python. I use scipy.misc.derivative.
Correct case:
def f(x):
return math.sin(x)
y=derivative(f,5.0,dx=1e-9)
print(y)
This will give a math.cos(5) right?
My problem is here. Since python accepts radians, we need to correct what is inside the sin function. I use math.radians.
If I code it again:
def f(x):
return math.sin(math.radians(x))
y=derivative(f,5.0,dx=1e-9)
print(y)
This will give an answer not equal to what I intended which should be math.cos(math.radians(5)).
Am i missing something?

You have to be consistent with the argument of the trigonometric function. Is not that "Python accepts radians", all programming languages I know use radians by default (including Python).
If you want to get the derivative of 5 degrees, yes, first convert to radians and then use it as the argument of the trigonometric function. Obviously, when you do
y=derivative(f,5.0,dx=1e-9)
using
def f(x):
return math.sin(x)
you get f'(x)=cos(x) evaluated at 5 (radians). If you want to check that the result is correct this is the function to check, not f'(x)=cos(math.radians(x)), which will give you another result.
If you want to pass 5 degrees, yes, you will need to get the radians first:
y=derivative(f,math.radians(5.0),dx=1e-9)
which will be the same as cos(math.radians(5)).
Here is a working example
from scipy.misc import derivative
import math
def f(x):
return math.sin(x)
def dfdx(x):
return math.cos(x)
y1 = derivative(f,5.0,dx=1e-9)
y2 = dfdx(5)
print(y1) # 0.28366
print(y2) # 0.28366

Related

Convert variable contents to string in python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last month.
This post was edited and submitted for review last month and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
I have a variable which has an equation .I'm trying convert the equation that the varibale has into a string and compute the results
Eg
def func1(x):
y = x + 5
return y, 'x+5'
x as input can vary since I'm iterating
through multiple values
Say
h[0][1] = 5
func1(h[0][1])
Output - 10, "h[0][1]+5"
Required result
I need x+5 as string and the computed result of y as a while calling func1
Eval and exec seemed like a probable solution but they perform the inverse of what is needed
I'm not sure I understand why you'd want this but given that the variable holding the equation would be known when coding, you could just wrap the equation in a function. Eg:
def add_five(x):
return (x + 5, "x + 5")
x = 10
y = add_five(x)
print("Answer is", y[0])
print("Equation is", y[1])

How to separe mathematical operation from math expression like: 'log(2*x)*cos(x)'? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 months ago.
Improve this question
I would like to separate this math expression 'log(2*x)*cos(x)' into 'log(2*x)' and 'cos(x)'. Im using Sympy to solve each part of the expression. I tried regex and ast.parse to separate math operation by parts but I didn't succeeded.
What I'm trying to do is to solve 'log(2*x)' first, 'cos(x)' second and then 'log(2*x)*cos(x)'. How can I get each math operation from an math expression?
You really shouldn't be doing this using regular expressions. You should be letting sympy parse it, and sympy separate it into terms.
>>> expr = log(2 * x) * cos(x)
>>> expr.as_ordered_factors()
[log(2*x), cos(x)]
Most of SymPy objects exposes the args attribute: it returns the arguments of an operator or a function. For example:
from sympy import *
var("x")
expr = log(2*x)*cos(x)
print(expr.args)
# out: (cos(x), log(2*x))
Here, your expression is a multiplication and args returned its factors.
Let's consider an addition:
expr = log(2*x) + cos(x)
print(expr.args)
# out: (cos(x), log(2*x))
Let's now consider a function:
expr = log(2*x)
print(expr.args)
# out: (2*x,)

Is there a way to plot a "function string" in python? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 months ago.
Improve this question
Example: The user types "(x^2 + 5)^3" into the terminal and the script plots the function like WolframAlpha would do.
Is there an easy way to do that in python?
The function might include abs(), sqrt() etc.
Thanks in advance for your responses
You could try using eval with an inputted X or default x:
import matplotlib.pyplot as plt
import numpy as np
import re
def get_variables(input_string):
count = 0
matches = re.findall(r'(?i)[a-z]', input_string)
return set(matches) #returns unique variables
function = input('Input Function: ')
variables = get_variables(function)
print(variables, type(variables), function)
varDict = {v: np.arange(100) for v in variables} #maps the variable names to some default range
for v in variables: #changes the function string to work with the newly defined variables
pattern = r'\b%s\b' %v
function = re.sub(pattern,r'varDict["%s"]' %v,function)
answer = eval(function) #evaluates the function
if len(variables) == 1:
plt.plot(*varDict.values(),answer) #plot the results, in this case two dimensional
else:
ax = plt.axes(projection="3d")
ax.plot3D(*varDict.values(),answer) # line
#ax.scatter3D(*varDict.values(),answer); #scatter
plt.show()
You can change the 3d settings if you want a scatterplot or add logic to make a shape (ie using meshgrid)
Just be sure that the eval statements are fully sanitized. This also requires the function to be inputted in python syntax (** not ^), unless you want to add functions to edit common syntax differences in the string.

How to implement this symbolic summation in python? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am trying to implement this summation, any help, please?
enter image description here
Considering that x is a list of numbers, this can be written as following:
H = '+'.join([f'x{i}*x{i+1}' for i in range(1, 21)])
>>>print(H)
'x1*x2+x2*x3+x3*x4+x4*x5+x5*x6+x6*x7+x7*x8+x8*x9+x9*x10+x10*x11+x11*x12+x12*x13+x13*x14+x14*x15+x15*x16+x16*x17+x17*x18+x18*x19+x19*x20+x20*x21'
You need a computer algebra system (CAS). There are a number of software packages in Python that implements CAS, for example, using sympy:
from sympy import *
i = symbols('i')
x = IndexedBase('x')
H = Sum(x[i] * x[i-1], (i, 1, 20))
This will produce H, a symbolic expression the represents the equation in your image.
Or, you can use summation instead to evaluate the Sum into a series of additions:
H_evaluated = summation(x[i] * x[i-1], (i, 1, 20))
or call the doit() function:
H_evaluated == H.doit()
You can try sympy online on https://live.sympy.org/ to play with sympy without installing it locally. Try this equation live

Sine square in python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Need help. How I can get sine square in python? Is there specific method or function?
Some supposedly obvious solutions are NOT suitable. Examples:
import numpy as np
import math
x = np.arange(0, 3, 0.5)
print([(math.sin(i) ** 2) for i in x])
print([math.sin(math.sin(i))for i in x])
# [0.0, 0.22984884706593015, 0.7080734182735712, 0.9949962483002227, 0.826821810431806, 0.3581689072683868]
#[0.0, 0.4612695550331807, 0.7456241416655579, 0.8401148815567654, 0.7890723435728884, 0.5633808209655248]
# or
x = np.arange(0, 3, 0.5)
print(np.sin(x) ** 2)
print(np.sin(np.sin(x)))
# [0. 0.22984885 0.70807342 0.99499625 0.82682181 0.35816891]
# [0. 0.46126956 0.74562414 0.84011488 0.78907234 0.56338082]
You need to look for math module in Python. See this.
math.sin(x) ** 2
You can also use math.pow(x,y). See this for how to raise a number x raised to the power y.
A small example program.
import math
rad = int(input("Enter radians: "))
print(math.sin(rad) ** 2)
If you want to convert from radians to degrees or vice-versa, have a look at this.
You will be safer if you use it as follows -
((math.sin(x)) ** 2)
Emphasis is to put the math.sin(x) inside bracket.

Categories