I need help on the fallowing: Lets say you ask the user for an ecuation it can be anything, for illustrating this example lets the the user choose this one:
x**5+3, and he also needs to assign any value of x, so it will look like this:
write the equation:
write the value of x you want to calculate:
my question is: how can you modify the x in the equation the user gave first to assign the value he wants to calculate?? in other worlds how can I make python calculate x**5+2, for x= any input value??
It looks like you want the user to enter an equation with variables and the value for the variable. And you want your code to evaluate the user input equation with user input value for the variable in the equation. Sounds like a candidate for eval():
In [185]: equation = 'x ** 5 + 2'
In [186]: x = 3
In [187]: eval(equation)
Out[187]: 245
Another example:
In [188]: equation = '(x + 99) * 2'
In [189]: x = 1
In [190]: eval(equation)
Out[190]: 200
Since in the above demonstration, equation is a string, it might as well be a user input. When you ask the user to input for the equation, store it in a variable (variable equation here). Then when you ask them for a value for the variables in the equation, cast it to int and just do a eval(equation) in your code.
Your question is hard to decipher, but if I understand correctly, you're talking about writing a function. Try the following:
def f(x):
return x**5 + 2
And you may use the function for any value of x, e.g., f(2).
This is relativity easily to do if you look up each piece of the puzzle (or coding problem in this case).
First you need user input:
x_string = input("Enter an x value: ")
Then you need to convert the input String into an integer:
x = int(x_string)
Finally you need to calculate the value and print it out:
results = x**5 + 2
print results
You seem to be new to Python, so I highly recommend looking up some tutorials (like this one).
Related
I have noticed that it's common for beginners to have the following simple logical error. Since they genuinely don't understand the problem, a) their questions can't really be said to be caused by a typo (a full explanation would be useful); b) they lack the understanding necessary to create a proper example, explain the problem with proper terminology, and ask clearly. So, I am asking on their behalf, to make a canonical duplicate target.
Consider this code example:
x = 1
y = x + 2
for _ in range(5):
x = x * 2 # so it will be 2 the first time, then 4, then 8, then 16, then 32
print(y)
Each time through the loop, x is doubled. Since y was defined as x + 2, why doesn't it change when x changes? How can I make it so that the value is automatically updated, and I get the expected output
4
6
10
18
34
?
Declarative programming
Many beginners expect Python to work this way, but it does not. Worse, they may inconsistently expect it to work that way. Carefully consider this line from the example:
x = x * 2
If assignments were like mathematical formulas, we'd have to solve for x here. The only possible (numeric) value for x would be zero, since any other number is not equal to twice that number. And how should we account for the fact that the code previously says x = 1? Isn't that a contradiction? Should we get an error message for trying to define x two different ways? Or expect x to blow up to infinity, as the program keeps trying to double the old value of x
Of course, none of those things happen. Like most programming languages in common use, Python is a declarative language, meaning that lines of code describe actions that occur in a defined order. Where there is a loop, the code inside the loop is repeated; where there is something like if/else, some code might be skipped; but in general, code within the same "block" simply happens in the order that it's written.
In the example, first x = 1 happens, so x is equal to 1. Then y = x + 2 happens, which makes y equal to 3 for the time being. This happened because of the assignment, not because of x having a value. Thus, when x changes later on in the code, that does not cause y to change.
Going with the (control) flow
So, how do we make y change? The simplest answer is: the same way that we gave it this value in the first place - by assignment, using =. In fact, thinking about the x = x * 2 code again, we already have seen how to do this.
In the example code, we want y to change multiple times - once each time through the loop, since that is where print(y) happens. What value should be assigned? It depends on x - the current value of x at that point in the process, which is determined by using... x. Just like how x = x * 2 checks the existing value of x, doubles it, and changes x to that doubled result, so we can write y = x + 2 to check the existing value of x, add two, and change y to be that new value.
Thus:
x = 1
for _ in range(5):
x = x * 2
y = x + 2
print(y)
All that changed is that the line y = x + 2 is now inside the loop. We want that update to happen every time that x = x * 2 happens, immediately after that happens (i.e., so that the change is made in time for the print(y)). So, that directly tells us where the code needs to go.
defining relationships
Suppose there were multiple places in the program where x changes:
x = x * 2
y = x + 2
print(y)
x = 24
y = x + 2
print(y)
Eventually, it will get annoying to remember to update y after every line of code that changes x. It's also a potential source of bugs, that will get worse as the program grows.
In the original code, the idea behind writing y = x + 2 was to express a relationship between x and y: we want the code to treat y as if it meant the same thing as x + 2, anywhere that it appears. In mathematical terms, we want to treat y as a function of x.
In Python, like most other programming languages, we express the mathematical concept of a function, using something called... a function. In Python specifically, we use the def function to write functions. It looks like:
def y(z):
return z + 2
We can write whatever code we like inside the function, and when the function is "called", that code will run, much like our existing "top-level" code runs. When Python first encounters the block starting with def, though, it only creates a function from that code - it doesn't run the code yet.
So, now we have something named y, which is a function that takes in some z value and gives back (i.e., returns) the result of calculating z + 2. We can call it by writing something like y(x), which will give it our existing x value and evaluate to the result of adding 2 to that value.
Notice that the z here is the function's own name for the value was passed in, and it does not have to match our own name for that value. In fact, we don't have to have our own name for that value at all: for example, we can write y(1), and the function will compute 3.
What do we mean by "evaluating to", or "giving back", or "returning"? Simply, the code that calls the function is an expression, just like 1 + 2, and when the value is computed, it gets used in place, in the same way. So, for example, a = y(1) will make a be equal to 3:
The function receives a value 1, calling it z internally.
The function computes z + 2, i.e. 1 + 2, getting a result of 3.
The function returns the result of 3.
That means that y(1) evaluated to 3; thus, the code proceeds as if we had put 3 where the y(1) is.
Now we have the equivalent of a = 3.
For more about using functions, see How do I get a result (output) from a function? How can I use the result later?.
Going back to the beginning of this section, we can therefore use calls to y directly for our prints:
x = x * 2
print(y(x))
x = 24
print(y(x))
We don't need to "update" y when x changes; instead, we determine the value when and where it is used. Of course, we technically could have done that anyway: it only matters that y is "correct" at the points where it's actually used for something. But by using the function, the logic for the x + 2 calculation is wrapped up, given a name, and put in a single place. We don't need to write x + 2 every time. It looks trivial in this example, but y(x) would do the trick no matter how complicated the calculation is, as long as x is the only needed input. The calculation only needs to be written once: inside the function definition, and everything else just says y(x).
It's also possible to make the y function use the x value directly from our "top-level" code, rather than passing it in explicitly. This can be useful, but in the general case it gets complicated and can make code much harder to understand and prone to bugs. For a proper understanding, please read Using global variables in a function and Short description of the scoping rules?.
"so i just started to learn python, now am against a real problem abt matrix i want to create a matrix by using an input from the user something like that : [[x,y],[x,y],[x,y],[x,y]],the first obvious solution is that to insert an array with 1D to a matrix on axis=0 but something went wrong with the dimensions on the console and also idk which function i use (like i said am new so looping through functions without knowing one of them really frustrated me)
so if anyone know how to do, and a speciallly the rules to append and insert to an array or a matrix without geeting some dimensional error would be very helpfull and thnx for ur time "
You could use a while loop that asks for user input until enough inputs have been passed through.
x = input('Enter x and y values (Ex. x,y): ')
lis, val = [], []
while 'n' not in x:
val = x.split(',')
lis.append(val)
x = input('Enter x and y values (Ex. x,y): ') # stop loop by typing n
print(lis)
To end the loop just type 'n'.
I have a problem, I have 2 lists with x and y values, and I would like to create a function based on these. But the problem is that I would like to build a function like this one:
f(x) = a * (x-b)**c
I already know scipy.interpolate but I couldn't find anything to return a function like this one.
is there a quite easy way to try to create the best function I can by searching which values of a,b and c match the most?
thanks for your help!
Edit:
here is what my current values of x and y look like:
I created this function :
def problem(values):
s = sum((y - values[0]*(x-values[1])**values[2])**2 for x,y in zip(X,Y))
return(s)
and I tried to find the best values of a,b and c with scipy.optimize.minimize but I don't know with which values of a,b and c I should start...
values = minimize(problem,(a,b,c))
(Edited to account for the OP's added code and sub-question.)
The general idea is to use a least-squares minimization to find the "best" values of a, b, and c. First define a function whose parameters are a, b, c that returns the sum of the squares of the differences between the given y values and the calculated values of a * (x-b)**c. (That function can be done as a one-liner.) Then use an optimization routine, such as one found in scipy, to minimize the value of that function value. Those values of a, b, c are what you want--use them to define your desired function.
There are a few details to examine, such as restrictions on the allowed values of a, b, c, but those depend somewhat on your lists of x and y values.
Now that you have shown a graph of your x and y values, I see that your values are all positive and the function is generally increasing. For that common situation I would use the initial values
a = 1.0
b = 0.0
c = 1.0
That gives a straight line through the origin, in fact the line y = x, which is often a decent first guess. In your case the x and y values have a very different scale, with y about a hundred times larger than x, so you would probably get better results with changing the value of a:
a = 100.0
b = 0.0
c = 1.0
I can see even better values and some restrictions on the end values but I would prefer to keep this answer more general and useful for other similar problems.
Your function problem() looks correct to me, though I would have written it a little differently for better clarity. Be sure to test it.
def problem (a , b, c, d):
return a * (x[d]-b)**c
I guess is what you are after. With D being what value of the X array. Not sure where Y comes into it.
I just start to learn python and learned about variables, input and basic math.
I been asked to write a mathematical exercise which has the parameters:
ax+by=c, dx+ey=f
a, b, c, d,e, f - the user input and than the program result and write
the answear for x, y
I did:
number1 = float(input('Insert a number1: '))
number2 = float(input('Insert a number2: '))
number3 = float(input('Insert a number3: '))
number4 = float(input('Insert a number4: '))
number5 = float(input('Insert a number:5 '))
number6 = float(input('Insert a number6: '))
I don't how to write an equation with two variables
x=number1+2.5*number2-number3 #(it should be looked like ax+by=c)
y=number5+2.5*number6-number4
ax+by=c AND dx+ey=f ==> x=(-by+ey-f+c)(a-d)
I also don't know why I can't write the variable inside print:
print('the value of x, y is') print((x))
You can write the above equations in matrix form.
You can find answer to (x,y) easily with this method. You just have to solve this matrix equation.
You can find the answer using numpy. (Or you just have to implement matrix inverse and multiplication your own)
import numpy as np
A = np.array([[a, b], [d, e]])
B = np.array([[c], [f]])
print(np.linalg.inv(A) # B)
Well, you must think in a way to solve a equation with 2 variables using a programming language, it's not so straightforward if you're not familiar with programming.
Think about the steps you have to take to solve that manually first and then try to implement that using Python, I'll try to help you with some guiding:
1- Find a number to multiply one of the equations so that you can "remove" one of the variables.
2- Sum both of the equations (forget about the variables for now, work only with their coefficients)
3- After summing both equations and storing the "new_coefficient" values and assuming you removed x you should have something like: ((e*step_1_number)+b)*y = f*step_1_number + c
4- With the previous step you'll be able to find your y value, after that it's pretty easy to find the x value.
I managed to do this using Python but I don't think it's going to be useful for you if I just post my code, try to work something out yourself, good luck!
I'm trying to make a program where you input the Slope, Y-Intercept, the minimum X and maximum X and then it will put a table of values that prints the "y" of each "x" essentially. I know I would have to use a for loop that uses the range function to take the range of the numbers they input so it will display that many items but I'm not sure what to do to make this work.
choice4=input("Slope (x): ")
choice5=input("Y-Intercept: ")
choice6=input("Minimum (x): ")
choice7=input("Maximum (x): ")
print("")
for items in range(int(choice6),int(choice7)):
print ((int(choice4) * x) + int(choice5))
You are almost there. The immediate issue is that you've called your loop variable items but then refer to it as x.
On a related note, you definitely want to give clearer names to your variables.
There are several smaller issues:
range() will exclude the final value, so you may need to account for that.
Instead of doing the same string-to-int conversions over and over again, you might want to do them just once.