python How to convert the input value into a mathematical function - python

How to convert an input value into a function!
x = int(input('Enter x value: '))
n = str(input('Enter n value: ')) #n= 2 * x ^ 2 - 2 * x + 2
def f(x,n):
return 2 * x ^ 2 - 2 * x + 2

Actually for what i understand, you don't need to input n.
x = int(input('Enter x value: '))
def f(x):
return 2*x**2 - 2*x+2
n = f(x)
Edit, after rereading others answer yes it probably wanted eval()
Just You can't write "2 * x ^ 2 - 2 * x + 2", the correct way is x**2 instead of x^2

You mean (?):
def f(x, n):
return n*x**2 - 2*x + 2
Or do you mean actually changing the operators?
The question as currently posed is mathematically impossible. You define x & n and are returning a function that you may or may not want to equate to n but its all defined entries.
Still guessing a little at the actual question, but if
y = input("Enter equation to evaluate")
and you expect y to be a quadratic, i.e.:
y = "a*x**b - c*x + d"
then you can get all them from:
import re
y1 = re.split('[* ]',y)
a = y1[0]
b = y1[3] #as there is a null ent between the ** we skip y1[2] and y[1] is 'x'
c = y1[5]
d = y1[8]
If you wanted the operators, then it gets a little harder to follow. So we'll cross that bridge if you do need them.
Or, as the others suggest, just use eval()!!

You could try to use eval.
x=int(input('...'))
n=input('...') # note that input returns a string
def f(x):
global n
return(eval(n))

I think,you are asking .
How to convert an input value into a mathmetical expression ?
If it is so !
use eval()
in python

Related

How to integrate expressions with sympy?

I have a problem integrating an expression:
I need to integrate all terms regardless of the variable,
the expression: -x + 2 * (x - 1)
Expected result: -x**2/2 + 2 * ((x - 1)**2) / 2
the code I'm using:
from sympy import *
x = symbols('x')
expr = - x + factor(2 * (x - 1))
int_1 = integrate(expr)
print(int_1)
generated result: x**2/2 - 2*x
I'm a python beginner...
Thank you!
If you check your result you will find it is the same as the original equation, so the answer is right:
>>> eq = -x + factor(2 * (x - 1))
>>> integrate(eq).diff()
x - 2
>>> eq.expand()
x - 2
This means that the result you got differed from the expected results by a constant and such cases are considered correct in terms of indefinite integration.
It looks like you already learned about autoexpansion (thus the use of factor to keep the 2 from distributing). What you may not realize, however, is that once you pass an expression to a routine it is not required to keep your expression in factored form. It looks like you were expecting that the x - 1 would be treated like x. We can simulate that as
>>> integrate(-x)+integrate(2*y).subs(y,x-1)
-x**2/2 + (x - 1)**2
Using y to represent x - 1 is ok in this case since the results only differ by a constant:
>>> (integrate(x-1) - integrate(y).subs(y ,x-1)).is_constant()
True
It will not, however, be true for all functions of x.
The problem is that you didn't pass any integration limits (from and to), so the only possible answer was the integrated formula.
If for example you want to integrate from 0 to inf, you need to pass this instead
from sympy import *
x = symbols('x')
expr = - x + factor(2 * (x - 1))
int_1 = integrate(expr, (x,0, float('inf')))
print(int_1)
replace 0 and/or float('inf') by any numbers you want to evaluate.

Making a table in Python 3(beginner)

So I just started learning Python 3 in school, and we had to make a function that
takes a as a parameter, chooses a reasonable value of x, and returns an estimate of the square root of a.
We also had to make a function to test it. We had to write a function named test_square_root that prints a table, where The first column is a number, a; the second column is the square root of a computed with the first function;
the third column is the square root computed by math.sqrt; the fourth column is the absolute value of the difference between the two estimates.
I wrote the first function to find the square root, but I don't know how to make a table like that. I've read other questions on here about tables in Python3 but I still don't know how to apply them to my function.
def mysqrt(a):
for x in range(1,int(1./2*a)):
while True:
y = (x + a/x) / 2
if y == x:
break
x = y
print(x)
print(mysqrt(16))
If you're allowed to use libraries
from tabulate import tabulate
from math import sqrt
def mysqrt(a):
for x in range(1, int(1 / 2 * a)):
while True:
y = (x + a / x) / 2
ifjl y == x:
break
x = y
return x
results = [(x, mysqrt(x), sqrt(x)) for x in range(10, 20)]
print(tabulate(results, headers=["num", "mysqrt", "sqrt"]))
Outputs
num mysqrt sqrt
----- -------- -------
10 3.16228 3.16228
11 3.31662 3.31662
12 3.4641 3.4641
13 3.60555 3.60555
14 3.74166 3.74166
15 3.87298 3.87298
16 4 4
17 4.12311 4.12311
18 4.24264 4.24264
19 4.3589 4.3589
Failing that there's plenty of examples on how to print tabular data (with and without libraries) here: Printing Lists as Tabular Data
def mysqrt(a):
for x in range(1, int(1 / 2 * a)):
while True:
y = (x + a / x) / 2
ifjl y == x:
break
x = y
return x
results = [(x, mysqrt(x), sqrt(x)) for x in range(10, 20)]
print(tabulate(results, headers=["num", "mysqrt", "sqrt"]

How to do numerical integration in python?

I can't install anything new I need to use the default python library and I have to integrate a function. I can get the value for any f(x) and I need to integrate from 0 to 6 for my function f(x).
In discrete form, integration is just summation, i.e.
where n is the number of samples. If we let b-a/n be dx (the 'width' of our sample) then we can write this in python as such:
def integrate(f, a, b, dx=0.1):
i = a
s = 0
while i <= b:
s += f(i)*dx
i += dx
return s
Note that we make use of higher-order functions here. Specifically, f is a function that is passed to integrate. a, b are our bounds and dx is 1/10 by default. This allows us to apply our new integration function to any function we wish, like so:
# the linear function, y = x
def linear(x):
return x
integrate(linear, 1, 6) // output: 17.85
# or using lamdba function we can write it directly in the argument
# here is the quadratic function, y=x^2
integrate(lambda x: x**2, 0, 10) // output: 338.35
You can use quadpy (out of my zoo of packages):
import numpy
import quadpy
def f(x):
return numpy.sin(x) - x
val, err = quadpy.quad(f, 0.0, 6.0)
print(val)
-17.96017028290743
def func():
print "F(x) = 2x + 3"
x = int(raw_input('Enter an integer value for x: '))
Fx = 2 * x + 3
return Fx
print func()
using the input function in python, you can randomly enter any number you want and get the function or if hard coding this this necessary you can use a for loop and append the numbers to a list for example
def func2():
print "F(x) = 2x + 3"
x = []
for numbers in range(1,7):
x.append(numbers)
upd = 0
for i in x:
Fx = 2 * x[upd] + 3
upd +=1
print Fx
print func2()
EDIT: if you would like the numbers to start counting from 0 set the first value in range to 0 instead of 1

Python, square root function?

I have compiled multiple attempts at this and have failed miserably, some assistance would be greatly appreciated.
The function should have one parameter without using the print statement. Using Newton's method it must return the estimated square root as its value. Adding a for loop to update the estimate 20 times, and using the return statement to come up with the final estimate.
so far I have...
from math import *
def newton_sqrt(x):
for i in range(1, 21)
srx = 0.5 * (1 + x / 1)
return srx
This is not an assignment just practice. I have looked around on this site and found helpful ways but nothing that is descriptive enough.
This is an implementation of the Newton's method,
def newton_sqrt(val):
def f(x):
return x**2-val
def derf(x):
return 2*x
guess =val
for i in range(1, 21):
guess = guess-f(guess)/derf(guess)
#print guess
return guess
newton_sqrt(2)
See here for how it works. derf is the derivative of f.
I urge you to look at the section on Wikipedia regarding applying Newton's method to finding the square root of a number.
The process generally works like this, our function is
f(x) = x2 - a
f'(x) = 2x
where a is the number we want to find the square root of.
Therefore, our estimates will be
xn+1 = xn - (xn2 - a) / (2xn)
So, if your initial guess is x<sub>0</sub>, then our estimates are
x1 = x0 - (x02 - x) / (2x0)
x2 = x1 - (x12 - x) / (2x1)
x3 = x2 - (x22 - x) / (2x2)
...
Converting this to code, taking our initial guess to be the function argument itself, we would have something like
def newton_sqrt(a):
x = a # initial guess
for i in range(20):
x -= (x*x - a) / (2.0*x) # apply the iterative process once
return x # return 20th estimate
Here's a small demo:
>>> def newton_sqrt(a):
... x = a
... for i in range(20):
... x -= (x*x - a) / (2.0*x)
... return x
...
>>> newton_sqrt(2)
1.414213562373095
>>> 2**0.5
1.4142135623730951
>>>
>>> newton_sqrt(3)
1.7320508075688774
>>> 3**0.5
1.7320508075688772
In your code you are not updating x (and consequently srx) as you loop.
One problem is that x/1 is not going to do much and another is that since x never changes all the iterations of the loop will do the same.
Expanding on your code a bit, you could add a guess as a parameter
from math import *
def newton_sqrt(x, guess):
val = x
for i in range(1, 21):
guess = (0.5 * (guess + val / guess));
return guess
print newton_sqrt(4, 3) # Returns 2.0
You probably want something more like:
def newton_sqrt(x):
srx = 1
for i in range(1, 21):
srx = 0.5 * (srx + x/srx)
return srx
newton_sqrt(2.)
# 1.4142135623730949
This both: 1) updates the answer at each iteration, and 2) uses something much closer to the correct formula (ie, no useless division by 1).

Adding two given floating point numbers in Python?

How would I create a method with Python to add floating point numbers that are in a list, without using libraries?. The teacher gave us this code, and I didn't understand it, could anyone else give me another example?
def msum(iterable):
"Full precision summation using multiple floats for intermediate values"
partials = [] # sorted, non-overlapping partial sums
for x in iterable:
i = 0
for y in partials:
if abs(x) < abs(y):
x, y = y, x
hi = x + y
lo = y - (hi - x)
if lo:
partials[i] = lo
i += 1
x = hi
partials[i:] = [x]
return sum(partials, 0.0)
A version of the Kahan algorithm in python would look like this:
def msum(input):
sum = 0.0
c = 0.0
for x in input:
y = x - c
t = sum + y
c = (t - sum) - y
sum = t
return sum
And what does "without using other libraries" even mean? Of course you could just have
def msum(input):
return sum(input)

Categories