how can write this formula in python? - python

how can i write a function that takes 2 integer parameters, a and b.
Inside the function I need calculate the value of x using the formula below (where the term 2a indicates that 2 is multiplied by a).
I'm quite lost with doing this can someone please give me a hint on how to start this code in python?

You can use the below method to achieve your goal.
# remember to import math
x = lambda a, b: (math.sqrt(b**2 - 1) + b)/(2 * a)
Now you can use this function:
x(5, 10) # gives 1.99498743710662 (roughly)

Here is how:
def x(a, b):
return (b+(b**2-1)**0.5)/(2*a)
In python, we use ** for power symbols.

Related

How to turn this code into a one-liner or make it shorter?

I am a middle school student and just started learning about functions. This code is about exponents, but I cannot use import math. Is there a way to make this code into a one-liner or make it shorter?
def power(a, n):
x = 1
if n == 0:
print(1)
elif n > 0:
for i in range(n):
x = x * a
else:
for i in range(-n):
x = x * a
return x
print(power(2, 5))
You can use the pow function instead of "x = x * a". Also even if you don't want to use that function, you can simplify it as "x *= a".
You could look into recursive functions, they are a bit tricky at first but are a good brain exercise.
A recursive power function would look like that :
def power(a, n):
if n == 0:
return 1
elif n == 1:
return a
else:
return a * power(a, n-1)
You can use the in-built operator **.
Example:
print(2**2) # Will return 4
Use the ** operator directly:
print(2 ** 5)
You can use this
**
which will return the value of 4 to the power of 3 (same as 4 * 4 * 4):
You can use ** This is an exponentiation operator.
def power(a, n):
return a**n
print(power(2, 5))
or simply use lambda function. You can read about it here.
print((lambda x,y:x**y)(2,5))
If you want to shorten your function with one line, you can use lambda statements like this: Shortening code with lambda statement in python
And you can use the ** builtin operator in place of multiplying the number over and over in a loop. So for example, 5**4 is equivalent to 5 * 5 * 5 * 5 and will give the exact same output.
P.S. I am also just beginning with programming, so I might not have the best answer.
If the goal is to use your own function. You can shorter an if with:
value_when_true if condition else value_when_false;
Putting a simple if-then-else statement on one line
I can see your overall need is to get the power of x.
If you can't use import math, then go with the inbuilt arithmetic operator for exponential that is **
Ex. You need 5 to the power 4 then code will be
print(5**4) # In one line
def power(b,n):
n=abs(n)
print(b**n)
print(power(2,-5))
well how about this here you can use the abs function to convert negative number to positive so no need for extra code simple use of ** can do everything

Computing Riemann-Liouville Integral using Sympy

New to calculus and not sure where this goes...
I'm trying to compute the Riemann-Liouville interpretation of the integral in Python using sympy. However the resulting integral when running my code between 0 and T contains T as a variable, which I do not want. What should I do to fix this?
Code:
def integral(f, order):
gamma_recip = 1/gamma(order)
T = sympy.Symbol('T')
r = sympy.Symbol('r')
eq = (T-r) ** order - 1
function_eq = eq * f(r)
integral = sympy.integrate(function_eq, (r, 0, T))
return integral
Equation:
Sample call as requested:
-0.333333333333333*T**3 + 0.0833333333333333*T**4.0
Function and order used:
def f(x):
return x**2
print(integral(f, 1.0))
Expected result:
r**3/3
Two issues:
you are using "T" as the integral limit so you will end up with that in the result; if you want "r" in the result, swap the use of T and r in your function
you didn't put parentheses around the order - 1 in your definition of eq; if you do you will (with your current code) get the expected T**3/3

How can I use sympy to find the error in approximation of a definite integral?

Our assignment is to use sympy to evaluate the exact definite integral of a function and then compare it with the approximation of the definite integral obtained from another python function we wrote. With simple polynomial functions my code works fine, but with a complicated sine function it keeps either breaking or returning nan.
from numpy import *
def simpson(f,a,b,n):
if n<=0 or n%2!=0:
print('Error: the number of subintervals must be a positive even number')
return float('NaN')
h = float(b - a) / float(n)
x = arange(a,b+h,h)
fx = f(x)
fx[1:n:2] *= 4.0
fx[2:n:2] *= 2.0
return (h/3.)*sum(fx)
this is in one file (simpandtrap) and gives the approximation for the definite integral of f from a to b using a simpson's rule approximation with n subintervals
from pylab import *
def s(x):
return x*sin(3./(x+(x==0)))
This is the function giving me trouble, in a file called assignment8functions
import assignment8functions as a
import SimpAndTrap as st
import sympy as sp
x = sp.symbols('x')
Exact_int_q = sp.integrate(a.q(x),(x,0,2)).evalf(25)
Exact_int_s = sp.integrate(x*sp.sin(3./(x)),(x,0,2)).evalf(25)
q(x) is another function we're supposed to use that everything works fine for - it's just a polynomial. When I try to do the integration the same way it breaks, so I had to put the function for s(x) directly into the call instead of importing the one from the other file
n = a.array([10,100,1000,10000,10000,1000000])
s_error_simp_array = a.zeros(6)
for i in a.arange(6):
s_error_simp_array[i] = abs(Exact_int_s - st.simpson(a.s,0,2,n[i])
here I try to find the error in the approximation. the problem is first of all that Exact_int_s is apparently -4.5*Si(zoo) + 8.16827746848576, and I have no idea what that's supposed to mean, and also that the simpson function always returns nan.
I know it's a lot of words and code, but does anybody know what's wrong?
To avoid the answer -4.5*Si(zoo)+ 8.--- just start the integration at a small positive number, e.g.:
x = sp.Symbol('x')
print sp.integrate( x * sin(3./x), (x, 0.000001, 2) )
and you'll get an answer like 1.0996940...
You can justify this because |s(x)| <= x for small x, so the interval [0, epsilon] can't contribute that much.
Btw - your simpson implemention seems to check out.

How can I create functions that handle polynomials?

I have these problems about polynomials and I've spent about 4 hours on this, but I just can't get it. I'm new to Python and programming and I've tried working it out on paper, but I just don't know.
Write and test a Python function negate(p) that negates the polynomial represented by the list of its coeffeicients p and returns a new polynomial (represented as a list). In other words, write a function that makes the list of numbers negative.
Write a Python function eval_polynomial(p, x) that returns the value of P(x), where P is the polynomial represented by the list of its coefficients p. For example, eval_polynomial([1, 0, 3], 2) should return 1*2^2 + 0*2 + 3 = 7. Use a single while loop.
Write and test a function multiply_by_one_term(p, a, k) that multiplies a given polynomial p, represented by a list of coefficients, by ax^k and returns the product as a new list.
I would really appreciate it if someone could help me.
I'd recommend using numpy.poly1d and numpy.polymul, where the coefficients are a0*x2 + a1*x + a2.
For example, to represent 3*x**2 + 2*x + 1:
p1 = numpy.poly1d([3,2,1])
And with the resulting poly1d object you can operate using *, / and so on...:
print(p1*p1)
# 4 3 2
#9 x + 12 x + 10 x + 4 x + 1
If you want to build your own functions, assuming that p contains the coefficients in order: a0 + a1*x + a2*x**2 + ...:
def eval_polynomial(p,x):
return sum((a*x**i for i,a in enumerate(p)))
def multiply_by_one_term(p, a, k):
return [0]*k + [a*i for i in p]
Note
My evaluate function uses exponentials, which can be avoided with Horner's rule, as posted in another answer, which is available in Numpy's polyval function
Please use Horner's Method instead!
For polynomials, you should consider Horner's Method. Its main feature is that computing a polynomial of order N requires only N multiplies and N additions -- no exponentials:
def eval_polynomial(P, x):
'''
Compute polynomial P(x) where P is a vector of coefficients, highest
order coefficient at P[0]. Uses Horner's Method.
'''
result = 0
for coeff in P:
result = x * result + coeff
return result
>>> eval_poly([1, 0, 3], 2)
7
You can work through it by hand, or follow the link to see how it works.

distance formula in python bug

I'm calculating the length of a line segment in python, but I don't understand why one piece of code gives me zero and the other gives the right answer.
This piece of code gives me zero:
def distance(a, b):
y = b[1]-a[1]
x = b[0]-a[0]
ans=y^2+x^2
return ans^(1/2)
This one gives me the right answer:
import math as math
def distance(a, b):
y = b[1]-a[1]
x = b[0]-a[0]
ans=y*y+x*x
return math.sqrt(ans)
Thank you.
In your first snippet you have written this:
ans^(1/2)
In Python the power operator is not ^, that's the XOR-operator. The power operator in Python is **. On top of that, in Python 2.x by default the result of the division of two integers is an integer, so 1/2 will evaluate as 0. The correct way would be this:
ans ** 0.5
And another thing, the function you have implemented here can be done a lot easier with math.hypot:
import math
def distance(a, b):
return math.hypot(b[0] - a[0], b[1] - a[1])
Try doing x**2 rather than x^2 ( which is XOR)
Or use the math.pow function
And also, 1/2 is 0 and not 0.5

Categories