ASKSAGE: Sage Q&A Forum - RSS feedhttps://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Thu, 17 Apr 2014 00:04:40 +0200Substitute and evaluatehttps://ask.sagemath.org/question/11357/substitute-and-evaluate/Hello, I would like to ask a really easy question:
How can I substitute a variable into an equation and have it evaluated simultaneously? If I have $f = a + b$ and would it to return $5$ if $a=2$ and $b=3$, how shall I proceed?
I've tried the following
a, b = var('a, b');
f = a + b;
a = 2; b = 3; f
But it returned `a+b`, which is not what I had in mind. Thanks for the help in advance!Wed, 16 Apr 2014 06:47:55 +0200https://ask.sagemath.org/question/11357/substitute-and-evaluate/Answer by Antlab for <p>Hello, I would like to ask a really easy question: </p>
<p>How can I substitute a variable into an equation and have it evaluated simultaneously? If I have $f = a + b$ and would it to return $5$ if $a=2$ and $b=3$, how shall I proceed?</p>
<p>I've tried the following</p>
<pre><code>a, b = var('a, b');
f = a + b;
a = 2; b = 3; f
</code></pre>
<p>But it returned <code>a+b</code>, which is not what I had in mind. Thanks for the help in advance!</p>
https://ask.sagemath.org/question/11357/substitute-and-evaluate/?answer=16115#post-id-16115You can use:
f (x,y)=x+y
a = 2; b = 3
f(a,b)
In this way you obtain 5, the desired result.
Actually you don't need x and y, you could use only a and b, but I put different names just to underline the mechanism. The first line defines the function f with generic variables. The last line calculates the value of f when you actually pass the values of the variables. It can be a bit confusing at first, I hope my example can help.Wed, 16 Apr 2014 09:44:14 +0200https://ask.sagemath.org/question/11357/substitute-and-evaluate/?answer=16115#post-id-16115Comment by Blackadder for <p>You can use:</p>
<p>f (x,y)=x+y</p>
<p>a = 2; b = 3</p>
<p>f(a,b)</p>
<p>In this way you obtain 5, the desired result.
Actually you don't need x and y, you could use only a and b, but I put different names just to underline the mechanism. The first line defines the function f with generic variables. The last line calculates the value of f when you actually pass the values of the variables. It can be a bit confusing at first, I hope my example can help.</p>
https://ask.sagemath.org/question/11357/substitute-and-evaluate/?comment=16199#post-id-16199Thanks Antlab!Thu, 17 Apr 2014 00:04:40 +0200https://ask.sagemath.org/question/11357/substitute-and-evaluate/?comment=16199#post-id-16199