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.Sun, 07 Aug 2022 17:36:19 +0200compose (non-)symbolic functionshttps://ask.sagemath.org/question/63574/compose-non-symbolic-functions/I wonder how to compose with a non-symbolic function, or, more generally, how to compose several functions, if some of them are non-symbolic.
In my concrete case, I wish to plot a transformed Gaussian distribution function (concretely, the Camp-Paulson approximation), comparing with a plot of probabilities of the binomial distribution this approximates.
What works, but is not flexible enough is:
import scipy.stats
n=20
p=0.05
binom_dist = scipy.stats.binom(n,p)
Bin=bar_chart([binom_dist.pmf(x) for x in range(n+1)],width=1)
T = RealDistribution('gaussian', 1)
CP=plot(lambda k:T.distribution_function(-1/3*(((0.95*k + 0.95)/(-0.05*k + 1.0))^(1/3)*(1/(k + 1) - 9) + 1/(k - 20) + 9)/sqrt(((0.95*k + 0.95)/(-0.05*k + 1.0))^(2/3)/(k + 1) - 1/(k - 20))),(k,-1,21) , rgbcolor=(0.8,0,0))
show(Bin+CP)
This option has the argument of T.distribution_function hard coded. I rather would have this computed from n and p, using another function. I have two approaches so far, that both don't work.
The first one has a function K computing the input to T.distribution_function like so:
import scipy.stats
n=20
p=0.05
binom_dist = scipy.stats.binom(n,p)
Bin=bar_chart([binom_dist.pmf(x) for x in range(n+1)],width=1)
T = RealDistribution('gaussian', 1)
#
a = 1/(9*n-9*k)
b = 1/(9*k+9)
r = (k+1)*(1-p)/(n*p-k*p)
c = (1-b)*r^(1/3)
μ = 1 - a
σ = sqrt(b*r^(2/3) + a)
def K(k): return (c - μ)/σ
#
CP=plot(lambda k:T.distribution_function(K(k)),(k,-1,21), rgbcolor=(0.8,0,0))
show(Bin+CP)
another alternative tries to set up the composed function before entering plot like so:
import scipy.stats
n=20
p=0.05
binom_dist = scipy.stats.binom(n,p)
Bin=bar_chart([binom_dist.pmf(x) for x in range(n+1)],width=1)
T = RealDistribution('gaussian', 1)
#
a = 1/(9*n-9*k)
b = 1/(9*k+9)
r = (k+1)*(1-p)/(n*p-k*p)
c = (1-b)*r^(1/3)
μ = 1 - a
σ = sqrt(b*r^(2/3) + a)
def distCPapprox(k): return T.distribution_function((c - μ)/σ)
#
CP=plot(lambda k:distCPapprox(k),(k,-1,21), rgbcolor=(0.8,0,0))
show(Bin+CP)
Both approaches don't work. I searched extensively for advice for function composition but couldn't find anything helpful. Your advice is greatly appreciated.oloidSun, 07 Aug 2022 17:36:19 +0200https://ask.sagemath.org/question/63574/How can I substitute an unknown function in an expression with a known function?https://ask.sagemath.org/question/60468/how-can-i-substitute-an-unknown-function-in-an-expression-with-a-known-function/I have defined an unknown function "p" with command
p=function("p")
Then I deduced another function, which contains "p":
aws(time)=921600*(-1333.33340000000*time + 2000)/(-3.36000004800000e6*p(time) + 3840000)
Now I would like to plot the function aws(time), by subtituting p(time) with a known function, like:
p(time)=time^0.54
I discovered I can't use .subs() as with free variables, so this doesn't work:
aws.subs(p(time)==time^0.54)
Then how can I substitute the known function, to be able to plot aws(time) finally?
KonstantinTue, 28 Dec 2021 03:11:56 +0100https://ask.sagemath.org/question/60468/How can I plot two parametric functions in a common coordinate system?https://ask.sagemath.org/question/60387/how-can-i-plot-two-parametric-functions-in-a-common-coordinate-system/ I can easily use parametric_plot() to plot 1 parametric function at once. For example
parametric_plot((sin(2*t),cos(3*t)),(t,0.0,9),aspect_ratio=1)
plots a nice Lissajous curve.
I also can plot a circle:
parametric_plot((sin(t),cos(t)),(t,0.0,9),aspect_ratio=1)
But how can I plot both of them in a common coordinate system?
I tried:
parametric_plot([(sin(2*t),cos(3*t)),(sin(t),cos(t))],(t,0.0,9),aspect_ratio=1)
Which doesn't work -> Last error message: ''tuple' object is not callable'
I also tried:
pl1=parametric_plot((sin(t),cos(t)),(t,0.0,9),aspect_ratio=1)
pl2=parametric_plot((sin(2*t),cos(3*t)),(t,0.0,9),aspect_ratio=1)
pl1.add_primitive(pl2)
pl1
Error: 'Graphics' object has no attribute 'options'
Then how can I use parametric_plot() to plot two parametric functions at once, in a common coordinate system?
KonstantinWed, 22 Dec 2021 23:45:43 +0100https://ask.sagemath.org/question/60387/Plot ratio of Bessel functionshttps://ask.sagemath.org/question/54361/plot-ratio-of-bessel-functions/I am new to SageMath and to this page. I'm running this version:
`SageMath version 9.2, Release Date: 2020-10-24 Using Python 3.8.5.`
I tried to plot the ratio of two functions related to Bessel functions.
First I defined `f` as the first derivative of `bessel_J(1, x)`
and `g`as `x*bessel_J(1, x)`:
f(x) = bessel_J(1, x)
g = derivative(f, x)
Then I defined `h` as their ratio:
h = g / (x*f)
Then, I tried to plot `h` with:
plot(h, (x, 0, 10))
The result is an empty plot, showing only the x, y axes, and this is not correct.
Am I doing something wrong? Is it possible to plot such a function and, if yes, how?wmaddoxSun, 22 Nov 2020 23:49:14 +0100https://ask.sagemath.org/question/54361/incorrect plot of simple defined function, but works with lambdahttps://ask.sagemath.org/question/48736/incorrect-plot-of-simple-defined-function-but-works-with-lambda/ I am trying to produce a plot of a simple defined function with a single if statement. The function works correctly as demonstrated by numerical values, but the corresponding plot is incorrect.
If I create the plot using a lambda definition of the function, the plot is correct. The sample code follows:
def h(x):
if x<0: return x
return x^2
for k in (-2..2):
print "(%d,%d)"% (k,h(k)),
print 'sample h(x) vs. x pairs'
H = plot(h(x),(-1.5,1.5),linestyle='dotted',color='red',thickness=3)
L = plot(lambda x: x if x<0 else x^2,(-1.5,1.5),figsize=3)
H+L
The following image shows the code and output in a Sagemath notebook.
As you can see the plot of h(x) does not properly evaluate the function if statement, but the lambda plot does.
![image description](https://snipboard.io/5C1Tey.jpg)holistoneThu, 14 Nov 2019 22:47:07 +0100https://ask.sagemath.org/question/48736/Plotting a linehttps://ask.sagemath.org/question/39441/plotting-a-line/I have
x,y = var('x y')
f = (2*x + 3*y == 0)
How do I plot it
plot(f) gives the error:
Traceback (click to the left of this block for traceback)
...
ValueError: Variable 'y' not found
And since it complained about y, why didn't it complain about x?
Also, where would I find the docs for this question?
And yes, I am a beginner at sagepmgWed, 08 Nov 2017 08:27:48 +0100https://ask.sagemath.org/question/39441/connecting plots by lineshttps://ask.sagemath.org/question/38845/connecting-plots-by-lines/There are 2 plots in a graphics_array (e.g. sin and cos). How do I "connect" these plots with connecting lines (e.g. a dashed line at angle=pi)?Chris_Mon, 18 Sep 2017 15:21:55 +0200https://ask.sagemath.org/question/38845/Plotting 2d vector fields – how to delay function evaluationhttps://ask.sagemath.org/question/36127/plotting-2d-vector-fields-how-to-delay-function-evaluation/I want to plot, for example, the following 2d vector field:
$$\vec{F}(x,y)= \begin{cases}
(0.1,0.1), & \text{for }r\le d_{min}\newline
\frac{\vec{r}}{r^3}, & \text{otherwise}.
\end{cases}$$
In one SageMath cell I have defined corresponding Python function:
reset()
dmin = 0.03
def my_vector_field_2D(x,y):
vector_field = vector([0.1,0.1])
r = vector([x,y])
if r.norm()>dmin:
vector_field = 1/ r.norm()^3 * r
return vector_field
In another cell, I use function `plot_vector_field` to plot the field:
var('x','y')
plot_vector_field(my_vector_field_2D(x,y),(x,-0.3,0.3),(y,-0.3,0.3))
However, function my_vector_field_2D(x,y) is evaluated before it is given to the function `plot_vector_field` and because in this evaluation my_vector_field_2D receives instead of numbers symbolic variables `x` and `y`, expression `r.norm()>dmin` is always `False`. As a result, my_vector_field_2D(x,y) is evalueted to: (0.100000000000000, 0.100000000000000). So the plotted filed is actually $\vec{F}(x,y)=(0.1,0.1)$ everywhere and that is not what I want.
How can I prevent this function evaluation?
I tried something that works with the `plot` function (provide the `plot` function with just the name of a function that you want to plot (without parameters) in order to prevent function evaluation):
plot_vector_field(my_vector_field_2D,(-0.3,0.3),(-0.3,0.3))
But here this method does not work: **TypeError**: 'function' object is not iterable.
**My first why question**: Why this does not work? It works for `plot` function and also for `contour_plot` function and probably for some other plot functions.
Then I found in the SageMath documentation that “when plotting non-symbolic functions, they should be wrapped in `lambda`”. So I tried:
plot_vector_field(lambda x,y:my_vector_field_2D(x,y),(-0.3,0.3),(-0.3,0.3))
And the same error popped up: **TypeError**: 'function' object is not iterable.
But this works:
plot_vector_field((lambda x,y:my_vector_field_2D(x,y)[0],lambda x,y:my_vector_field_2D(x,y)[1]),(-0.3,0.3),(-0.3,0.3))
**My second why question**: Why do I need two `lambda` functions or why do I need to manually decompose vector returned by my_vector_field_2D function into its two components?
vkFri, 30 Dec 2016 18:54:07 +0100https://ask.sagemath.org/question/36127/How do I plot a function undefined in some areas?https://ask.sagemath.org/question/34850/how-do-i-plot-a-function-undefined-in-some-areas/ I am trying to plot `f(x,z)` which is undefined in some areas. When I try to plot some other function, I can get it to work easily because Sage restricts the plot to the area where the function is real. E.g.:
plot3d(sqrt(1-x^2-y^2), (x,-5,5), (y,-5,5))
The border is a bit weird, but it works. I cannot get a working plot with my code, however. I also tried to wrap the function with a `try ... except` statement but I don't know what to return:
var("x y z")
def wrap(exp, a, b):
try:
return exp(x=a, z=b)
except ValueError:
return None
plot3d(lambda x,y: wrap(f, x, y), (x, -t, t), (y, -t, t)).show(aspect_ratio=1)
My function is `f` and it contains variables `x` and `z`.LazzaSun, 18 Sep 2016 22:02:42 +0200https://ask.sagemath.org/question/34850/Plot in a functionhttps://ask.sagemath.org/question/31792/plot-in-a-function/Hello,
Is it normal that i can't plot in a function ?
Without a function:
plot(point([1, 1]))
![image description](http://zupimages.net/up/15/52/vu8t.png)
With a function:
def toto():
plot(point([1, 1]))
toto()
![image description](http://zupimages.net/up/15/52/90ma.png)
Thanks in advance !NeabfiWed, 23 Dec 2015 13:54:43 +0100https://ask.sagemath.org/question/31792/Plotting a 2d functionhttps://ask.sagemath.org/question/25122/plotting-a-2d-function/This should be easy, I want to make a nice colour plot of a 2d function where colour denotes the function value.
I can do
> y=var('y')
> f=y^2
> plot(f)
and I get a nice plot.
If I try
> y=var('y')
> f=y^2+x^2
> plot(f)
Then sage tells me it can't find the variable y. Which is ridiculous, since y is in the same place as when I tried to plot a 1d function of y. Anyway, I tried googling to find a function within sage to achieve this (without resorting to excessive matplotlib syntax) and had no success so thought I'd ask a question here. Intuitively, the second case is hardly more complicated than the former so there should be a simple function that can realize this for me.
Many thanks!DarwinThu, 04 Dec 2014 17:53:03 +0100https://ask.sagemath.org/question/25122/Defining a periodic function.https://ask.sagemath.org/question/10539/defining-a-periodic-function/Hi,
I am a new sage user. I'd like to define simple periodic maps over \R which plot and integrate correctly (eg. a square signal (which of course is discontinuous but which I would still like to be able to plot in a way that makes it clear that the function is not multivalued at discontinuity points)).
I tried different approaches none of which gave satisfactory results.
Any hint on how to do that nicely (or what would be the obstacles)?
Thank youlcSun, 15 Sep 2013 06:57:16 +0200https://ask.sagemath.org/question/10539/plot() command in load .sage scripthttps://ask.sagemath.org/question/10143/plot-command-in-load-sage-script/Hi experts!!
When i save a .sage script (like 'lalala.sage') with the next text:
var('x')
f(x)=4*sin(x)
plot(f,(x,-3,3))
and then, in SAGE, i put
load('lalala.sage')
there doesn't appears the graph of the f(x), but if i put in SAGE (after load 'lalala.sage'):
plot(f,(x,-3,3))
then the graph of f(x) appears
The question is: Why doesn't appears the graph of f(x) when i load the scipt 'lalala.sage'?
Thanks so much!!
Best regardsmresimulatorMon, 20 May 2013 17:39:17 +0200https://ask.sagemath.org/question/10143/Plotting a recursive functionhttps://ask.sagemath.org/question/9729/plotting-a-recursive-function/I'm trying to plot different iterations of the [Cantor function](http://en.wikipedia.org/wiki/Cantor_function) using the iterative definition:
Let 0(x) = x.
Then,
Let n+1(x) = 1/2*n(3x), when 0 <= x < 1/3;
Let n+1(x) = 1/2, when 1/3 <= x < 2/3;
Let n+1(x) = 1/2 + 1/2*n(3x - 2), when 2/3 <= x <= 1.
I extended it to be 0 when x<0 and 1 when x>1.
The function I have defined returns the correct values for a specific iteration and a specific x, but it is not plotting how I would like it to. When I plot it, I just get a horizontal line at 1.
def cantor(z,iter=0):
#'z' is the x value
#'iter' is the number of iterations in the iterative process
if iter == 0:
val = z
elif z<0:
val = 0
elif z<(1/3):
val = (1/2)*cantor(3*z,iter-1)
elif z<=(2/3):
val = (1/2)
elif z<=1:
val = (1/2)+(1/2)*cantor(3*z-2,iter-1)
else:
val = 1
return val
plot(cantor(x,0)) #this works
plot(cantor(x,1)) #this doesn't work
Thanks in advance for any help.propterhocTue, 22 Jan 2013 01:07:02 +0100https://ask.sagemath.org/question/9729/plot issue with a self-defined piecewise functionhttps://ask.sagemath.org/question/8643/plot-issue-with-a-self-defined-piecewise-function/The following code produces an error:
def f(x):
if x>3:
return(x^2)
if x<=3:
return(3*x)
plot(f(x),(x,0,5))
BUT, the code below works.
def f(x):
if x>3:
return(x^2)
if x<=3:
return(3*x)
plot(lambda x: f(x),(x,0,5))
So, my questions are:
(1) why do you need the lambda function? and
(2) when do you have to do this?
calc314Wed, 18 Jan 2012 16:10:48 +0100https://ask.sagemath.org/question/8643/defining periodic functionshttps://ask.sagemath.org/question/7799/defining-periodic-functions/I'm trying to plot approximations to McCarthy's continuous nowhere differentiable function [(PDF file)](http://www-formal.stanford.edu/jmc/weierstrass.pdf). The definition is like this: first, define a function $g(x)$ to be a triangle wave:
$$g(x) = 1+x \ \text{ if } -2 \leq x \leq 0, \quad g(x) = 1-x \ \text{ if } 0 \leq x \leq 2$$
and then require $g$ to be periodic with period 4. Then McCarthy's function is
$$f(x) = \sum_{n=1}^{\infty} 2^{-n} g(2^{2^{n}} x).$$
How should I set this up in Sage? If I define g(x) by
def g(x):
if -2 <= x and x <= 0:
return 1+x
elif 0 < x and x <= 2:
return 1-x
elif x > 2:
return g(x-4)
return g(x+4)
and then try to plot the 4th partial sum for $f(x)$, I get an error about "maximum recursion depth exceeded". I get the same error if I try `plot(g, (x, 10000, 10010))`. Is there a better way of defining a periodic function like $g$? I guess I can do something like `while x>2: x = x-4`, etc., but my real question is, can I define such a function symbolically rather than as a Python function?
Edit: my current fastest version of this function is as follows:
%cython
def g(float x):
x = abs(x)
x = 4.0*(x/4.0 - int(x/4.0))
if x <= 2:
return 1-x
return -3+x
Even if it's not possible to write this symbolically, how can I speed this up?John PalmieriWed, 08 Dec 2010 13:36:18 +0100https://ask.sagemath.org/question/7799/