Ask Your Question

Emmanuel Charpentier's profile - activity

2019-11-20 13:00:16 -0600 answered a question How to find a short form of recursive defined sequences?

This is possible with Sagemath: Maxima and Sympy have tools to work on recurrences, whose interfaces in Sage are, to say the least, not proeminently presented in Sagemath's documentation. See § 10.2 of this excellent (free) book, and Maxima's and Sympy's documentations...

2019-11-20 12:50:08 -0600 commented question Strange behavior of plot

Before what ?

2019-11-20 11:27:07 -0600 commented answer How to find all roots with solve?

On what subject ? Getting all Sympy results in Sage u=is a large work, already undertaken notably by someone whose trac login is rws and whose name escapes me presently (getting old isn't fun...). The present occurrence is but a special case...

Do you suggest a "sympy usability" metaticket ?

The Mathematica interface has other problems, most notably the lack of correct Mathematica<-->Sage conversions. E. g., try to use arctan in a Mathematica call...

sage: mathematica.Integrate(arctan(x),x)
Integrate[Arctan[x], x]

This is true in the reverse direction also 'Sage complains of the lack of a function arcTan...)

Since Mathematica isn't free, I doubt that polishing its interface can be considered high-priority. Sympy's can, however...

2019-11-19 13:53:29 -0600 answered a question obtaining all numerical roots of a function in an interval

Formally, it can't be done. For example, $\sin\displaystyle\frac{1}{x}$ has an infinity of roots between -1 and 1...

2019-11-19 13:40:05 -0600 answered a question How to find all roots with solve?

Sympy offers us a solution, but sage is not (yet) ready to parse it totally. But with a little Sympy's doc reading and a little manual unscrewing, one can get it:

sage: [u.args[0].args[1]._sage_() for u in c_p.solve(theta, algorithm="sympy")]
[2*pi*n + arctan((2*pi - 5)/(pi*sqrt(20/pi - 25/pi^2 + 12))),
 pi + 2*pi*n - arctan((2*pi - 5)/(pi*sqrt(20/pi - 25/pi^2 + 12))),
 -pi + 2*pi*n + arctan(1/2*(2*pi + 5)/(pi*sqrt(-5/pi - 25/4/pi^2 + 3))),
 2*pi + 2*pi*n - arctan(1/2*(2*pi + 5)/(pi*sqrt(-5/pi - 25/4/pi^2 + 3)))]

A bit of fooling around with latex and string splicing allows us to get the $\LaTeX$ form:

$$2 \pi n + \arctan\left(\frac{2 \pi - 5}{\pi \sqrt{\frac{20}{\pi} - \frac{25}{\pi^{2}} + 12}}\right)$$ $$\pi + 2 \pi n - \arctan\left(\frac{2 \pi - 5}{\pi \sqrt{\frac{20}{\pi} - \frac{25}{\pi^{2}} + 12}}\right)$$ $$-\pi + 2 \pi n + \arctan\left(\frac{2 \pi + 5}{2 \pi \sqrt{-\frac{5}{\pi} - \frac{25}{4 \pi^{2}} + 3}}\right)$$ $$2 \pi + 2 \pi n - \arctan\left(\frac{2 \pi + 5}{2 \pi \sqrt{-\frac{5}{\pi} - \frac{25}{4 \pi^{2}} + 3}}\right)$$

Note: Maxima could also get it (via to_poly_solve), but gives pompous pedantic nonsense involving logs of complex expressions, probably due to the domain:complex default...

Note 2: Substituting these values in c_p gets rid of the trig functions easily (via trig_reduce() after declaring n integer...). However, the resulting expressions involve sums ad products of scalar and square roots values ; proving them to be 0 is another possibly nontrivial problem... It can be "checked" numerically, and formally proved for the last two:

sage: L2=[u.args[0].args[1]._sage_() for u in c_p.solve(theta, algorithm="sympy")]
sage: [c_p.subs(theta==u).trig_reduce().n() for u in L2]

sage: [bool(c_p.subs(theta==u).trig_reduce()==0) for u in L2]
[False, False, True, True]

EDIT : A few notes for the terminally curious:

fricas and giac give the same results as maxima (i. e. Sage).

I have been unable to obtain no-nonsensical results from to_poly_solve.

One can also screw around Mathematica's answers to get another form of the results (closer to what Sage/Maxima gives) :

sage: var("k", domain="integer")
sage: LM=[u[1][2][1].sage(locals={"C":lambda x:k}) for u in mathematica.Solve(c_p
....: ==0, theta)]
sage: LM
[pi + 2*pi*k + arcsin(1/4*(2*pi + 5)/pi),
 2*pi*k - arcsin(1/4*(2*pi + 5)/pi),
 pi + 2*pi*k - arcsin(1/4*(2*pi - 5)/pi),
 2*pi*k + arcsin(1/4*(2*pi - 5)/pi)]

which is:

$$\pi + 2 \pi k + \arcsin\left(\frac{2 \pi + 5}{4 \pi}\right)$$ $$2 \pi k - \arcsin\left(\frac{2 \pi + 5}{4 \pi}\right)$$ $$\pi + 2 \pi k - \arcsin\left(\frac{2 \pi - 5}{4 \pi}\right)$$ $$2 \pi k + \arcsin\left(\frac{2 \pi - 5}{4 \pi}\right)$$

which turns out to be somewhat easier to check/prove:

sage: [c_p.subs(theta==u).trig_reduce().expand() for u in LM]
[0, 0, 0, 0]
2019-11-17 16:39:13 -0600 answered a question import error on debian

WorksForMe (TM). On Python3-based Sage 9.0.beta5 running on Debian testing:

charpent@zen-book-flip:~$ cat ~/Temporaire/Sagemath/AskSage48780/import-error-on-debian.sage
R, W, R_S, H, H_S, S = var('R W R_S H H_S S')
equations = [ S                 == R_S + H_S,
              R_S               == H_S,
              (R + R_S + W)     == 3 * R_S,
              0.8*(W+R+R_S)     == H + H_S,
              W/(W+R+R_S)       == 0.6,
              R + W+ S +H       == 0.85]
print(solve(equations,[R, W, R_S, H, H_S,S ], algorithm="sympy", solution_dict=False))
charpent@zen-book-flip:~$ sage ~/Temporaire/Sagemath/AskSage48780/import-error-on-debian.sage
[{R: 0.0314814814814815, W: 0.283333333333333, R_S: 0.157407407407407, H: 0.220370370370370, H_S: 0.157407407407407, S: 0.314814814814815}]

You'll note that Sympy insists on giving its solutions as dictionaries...

You'll note that your error stack starts by quoting lines from your input file, whoch bears very little semblance to what you have given us as your input file.

Did you play with hard links recently ? or have had disk troubles ?

2019-11-15 11:49:17 -0600 commented answer incorrect plot of simple defined function, but works with lambda

Yon can also plot(min_symbolic(sin(x),cos(x)),(x,0,2*pi))...

2019-11-15 00:10:09 -0600 answered a question incorrect plot of simple defined function, but works with lambda

Another classic Sage trap...

sage: def h(x):
....:     if x<0: return x
....:     return x^2

What happens ?

  • h is indeed a function:

    sage: h
    <function h at 0x7fdd6ede8d90>
  • It works:

    sage: h(-1.5)
  • But ... what is h(x) ?

    sage: h(x)
  • But why ?


sage: x<0
x < 0

When the Python variable x is bound to the symbolic variable x, the expression x<0evaluates to itself, which is neither False nor 0. Therefore, it is logically equivalent to True, and the if... statement of h evaluates to x^2.

Now, in the call plot(h(x),(-1.5,1.5)), the first argument is evaluated as the expression x^2, which is then evaluated for all values specified by the second argument (whether this one is (-1.5, 1.5) or (x, -1.5, 1.5)).

Oppose this to plot(h, (-1.5, 1.5)), where the first argument is evaluated to a function, which is then called for all the values specified by the second argument.

This is also true in the plot(lambda x: x if x<0 else x, (-1.5, 1.5)) call, whose first argument evaluates to a function:

sage: lambda x: x if x<0 else x^2
<function <lambda> at 0x7fdd67e2b9d8>

This trap is somewhat specific to Sage, since Python does not have evaluable symbolic expressions...


2019-11-12 06:55:18 -0600 commented answer Sending parameters

The metacommentary is, IMHO, necessary, not only for this case, but for a multitude of other cases (reviewiong "old" quiestions is instructive...).

2019-11-12 00:42:04 -0600 answered a question Sending parameters

From the Python docs:


The list of command line arguments passed to a Python script. argv[0] is the script name (it is operating system dependent whether this is a full pathname or not). If the command was executed using the -c command line option to the interpreter, argv[0] is set to the string '-c'. If no script name was passed to the Python interpreter, argv[0] is the empty string.

To loop over the standard input, or the list of files given on the command line, see the fileinput module.

Note On Unix, command line arguments are passed by bytes from OS. Python decodes them with filesystem encoding and “surrogateescape” error handler. When you need original bytes, you can get it by [os.fsencode(arg) for arg in sys.argv].

2019-11-08 01:11:26 -0600 commented answer Does sagemath move asterisks down?

Yes, I meant minted.My bloody aging neurons...

2019-11-07 14:37:21 -0600 answered a question Does sagemath move asterisks down?

I don't have your font. But I can reproduce your problem while using the "Inconsolata" mono font.

OTOH, I obtain correct results by using minted instead of listings (up to the specialization of the font: see below). Which I do routinely anyway, since listings doesn't support easily anything else than US "english", which is an excruciating pain in the *$$ for about 96% of this planet's population...

(while I'm sure that they exist, I didn't take the time to look up the necessary idioms to set the font options you desire for your listings. I'll do that if/when I have the time...).


  1. It is possibly a bug of listings when used in/triggered by Sagetex.

  2. Using a modern alternative (i. e. listings) solves the problem (with the obvious drawback to have to allow -shell-escape, which is a nice security hole...).

It might be worthy to open an issue on the Sagetex Github page...

As for fixing that up yourself, well... First look if listings used alone (i. e. by typesetting a Sage snippet with \lstinputlisting, IIRC) gives you correct results or not.

If so, the problem is in SageTeX, in which case you have now a reasonable chance to get your patch in a future version of SageTeX, now that the Sage core team can act on it.

If not, the problem is in listings. Then ... good luck to get a fix: the authors of listings seem to be unreacheable, and about 15 years of pleas to get support for no-US-ASCII have been ignored...

2019-11-07 13:38:32 -0600 commented answer How to create 31-tuples with nonnegative entries that sum to 1

Indeed. But the uniformity wasn't specified in the problem statement... and i'm lazy :-). Generating a simplex q=with uniform density isn't that simple...

2019-11-07 02:37:24 -0600 commented question maximizing sum over feasible set of vectors

Okay. But there are still contradictions : for example, $E(\underline{\alpha})$ is definded as a sum iover pairs $A,\,B$ with $A\cap B\neq\emptyset$, but with the "precision";

disjoint nonempty sets $A$ and $B$

which is contradictory (disjoint sets are defined by an empty intersection...).

The original poster should attempt to clarify what he's after : we (I, for the least) have limited time to play games...

2019-11-06 12:46:07 -0600 commented question maximizing sum over feasible set of vectors

Okay. you want to (pedantly) number the components of $\underline{\alpha}$ in binary. And to ignore $\alpha_0$. Right ?

$A$ is therefore an index of the 31 components of $\underline{\alpha}$,$v(\underline{\alpha})$ is $\sum_{i=1}^{32}\alpha_{i-1}$. Still right ?

2019-11-06 12:37:42 -0600 commented answer Having trouble importing the lazy_laurent_series module

Your Sage is too old (8.1 is quite old by today's standards...). From the doc:

AUTHORS: Kwankyu Lee (2019-02-24): initial version

2019-11-06 04:48:27 -0600 commented answer Latex multicolumn is not recognized

Nils, your answer is perfectly valid and correct. Just less verbose than mine...

2019-11-06 04:45:55 -0600 commented answer How to create 31-tuples with nonnegative entries that sum to 1

Clapclapclapclapclap ! Very nice (much more general than my ad hoc solution...).

2019-11-05 22:22:56 -0600 commented question maximizing sum over feasible set of vectors

Also, go easy on (pseudo-)formalism: I can't make head or tails of your definition of $\underline{\alpha}$... For another example, you define $A$ as a subset of $[5]$ ; but now, what is $\log(|A|)$ ???

2019-11-05 22:12:10 -0600 answered a question How to create 31-tuples with nonnegative entries that sum to 1

As already pointed out by commenters, there are infinitely many such tuples. One way to generate them is:

def R31S1():
    A=[random() for u in range(31)]
    return tuple([u/S for u in A])

Let's check:

sage: T=R31S1()
sage: type(T)
<class 'tuple'>
sage: len(T)
sage: sum(T)
sage: all([u>=0 and u<1 for u in T])
sage: T

All of this is basic Python, nothing Sage-specific...


2019-11-05 21:49:25 -0600 commented question maximizing sum over feasible set of vectors

Homework ?

2019-11-05 13:15:59 -0600 answered a question Latex multicolumn is not recognized


sage: latex(GF(3).multiplication_table())

In a console (or in emacs's sage-shell-view), view(GF(3).addition_table()) gets me this:

image description

Sage's view uses Mathjax by default, but reverts to $\LaTeX$ when the latex string contains some "trigger" commands (this can be customized via latex.add_to_mathjax_avoid_list).

But, indeed, in a Jupyter notebook, this fails (not only on \multicolumn but also on {\setlength{\arraycolsep}{2ex}), probably because the notebook can't use $\LaTeX$\, and mathjax isn't a complete implementation if it).

By the way, the mathjax implementation of the present server has the same problem: A cut'n'paste of the $\LaTeX$ string generating the (correct) representation of the multiplication table gives this:

$${\setlength{\arraycolsep}{2ex} \begin{array}{r|*{3}{r}} \multicolumn{1}{c|}{\ast}&a&b&c\\hline {}a&a&a&a\ {}b&a&b&c\ {}c&a&c&b\ \end{array}}$$

This can probably worked around by saving the latex text, compiling it with an external LaTeX installation, converting the output to, say, .png and displaying it in the notebook. An utility function might be written for that.

One more reason to use $\LaTeX$ an Sagetex (or pythontex (or org-mode))...


2019-11-05 01:51:46 -0600 answered a question Having trouble importing the lazy_laurent_series module

WorksForMe(TM). On a Python 3-based 9.0.beta3 :

sage: from sage.rings.laurent_series_ring import *
sage: L.<z> = LazyLaurentSeriesRing(QQ)
sage: L.category()
Category of magmas and additive magmas
sage: 1/(1 - z)
1 + z + z^2 + z^3 + z^4 + z^5 + z^6 + ...
sage: 1/(1 - z) == 1/(1 - z)

NOTE : from the doc:

The definition of Laurent series rings is not initially imported into the global namespace. You need to import it explicitly to use it.


2019-11-03 16:08:58 -0600 answered a question linear algebra derivative expressions

I'm out of my depth here, but I'd suggest a look at the Manifolds project, implemented in Sagemath.

2019-11-02 07:11:56 -0600 received badge  Nice Answer (source)
2019-11-01 09:17:50 -0600 commented question dynamic library not found

Could you post this on sage-support, and specify your installation (platform, mode of installation (i. e. precompiled package or self-compiled), environment, presence of other Python environments (conda and such...) ) ?

2019-11-01 03:53:39 -0600 answered a question How to solve this algebraic equation by SageMath (rather than by hand)
sage: u,r,t,a = var('u','r','t','a') 
sage: g = (sqrt(a^2 + (r+t)^2) - sqrt(a^2 + (r-t)^2))/(2*r)
sage: E = u == g ; E
u == 1/2*(sqrt(a^2 + (r + t)^2) - sqrt(a^2 + (r - t)^2))/r

This can't be solved "automagically" by Sage's default solver (i. e. Maxima's).

However, there are some worarounds. First, one can "pilot" Sage's default solver to the solution. First, we try to eliminate the radicals by squaring :

sage: E2 = (E^2).expand(); E2
u^2 == 1/2*a^2/r^2 + 1/2*t^2/r^2 - 1/2*sqrt(a^2 + r^2 + 2*r*t + t^2)*sqrt(a^2 + r^2 - 2*r*t + t^2)/r^2 + 1/2

isolating the radicals :

sage: RP=E2.rhs().operands()[2] ; RP
-1/2*sqrt(a^2 + r^2 + 2*r*t + t^2)*sqrt(a^2 + r^2 - 2*r*t + t^2)/r^2
sage: PP=E2.rhs()-RP
sage: E2-PP
u^2 - 1/2*a^2/r^2 - 1/2*t^2/r^2 - 1/2 == -1/2*sqrt(a^2 + r^2 + 2*r*t + t^2)*sqrt(a^2 + r^2 - 2*r*t + t^2)/r^2

and squaring again :

sage: E4=((E2-PP)^2).expand(); E4
u^4 - a^2*u^2/r^2 - t^2*u^2/r^2 - u^2 + 1/4*a^4/r^4 + 1/2*a^2/r^2 + 1/2*a^2*t^2/r^4 + 1/2*t^2/r^2 + 1/4*t^4/r^4 + 1/4 == 1/4*a^4/r^4 + 1/2*a^2/r^2 + 1/2*a^2*t^2/r^4 - 1/2*t^2/r^2 + 1/4*t^4/r^4 + 1/4

Any solution of E is solution of E4, which is now a polynomial equation in t ultimately of the form A*t^2+B==0. In turns out that Maxima can solve it:

sage: E4.solve(t)
[t == -sqrt(r^2*u^2/(u^2 - 1) - a^2/(u^2 - 1) - r^2/(u^2 - 1))*u, t == sqrt(r^2*u^2/(u^2 - 1) - a^2/(u^2 - 1) - r^2/(u^2 - 1))*u]

$$\left[t = -\sqrt{\frac{r^{2} u^{2}}{u^{2} - 1} - \frac{a^{2}}{u^{2} - 1} - \frac{r^{2}}{u^{2} - 1}} u, t = \sqrt{\frac{r^{2} u^{2}}{u^{2} - 1} - \frac{a^{2}}{u^{2} - 1} - \frac{r^{2}}{u^{2} - 1}} u\right]$$

Since we have squared our equations (twice..), we may have introduced "spurious solutions. The candidate solutions above must be checked. This is not trivial, and is therefore cowardly left to the reader "as an exercise".

It turns out that sympy can solve the original equation E, but that Sage is currently unable to translate it back to Sage: sage: SS=E.solve(t, algorithm="sympy"); SS

ConditionSet(t, Eq(-2*r*u - sqrt(a**2 + (r - t)**2) + sqrt(a**2 + (r + t)**2), 0), {-u*sqrt((-a**2 + r**2*u**2 - r**2)/((u - 1)*(u + 1))), u*sqrt((-a**2 + r**2*u**2 - r**2)/((u - 1)*(u + 1)))})
sage: SS._sage_()
AttributeError                            Traceback (most recent call last)
<ipython-input-180-8b468472da8b> in <module>()
----> 1 SS._sage_()

AttributeError: 'ConditionSet' object has no attribute '_sage_'

One can manually extract the roots proposed by sympy:

sage: [u._sage_() for u in SS.args[2].args]
[u*sqrt((r^2*u^2 - a^2 - r^2)/((u + 1)*(u - 1))),
 -u*sqrt((r^2*u^2 - a^2 - r^2)/((u + 1)*(u - 1)))]

which turn out to be the same as those proposed by Maxima:

$$\left[u \sqrt{\frac{r^{2} u^{2} - a^{2} - r^{2}}{{\left(u + 1\right)} {\left(u - 1\right)}}}, -u \sqrt{\frac{r^{2} u^{2} - a^{2} - r^{2}}{{\left(u + 1\right)} {\left(u - 1\right)}}}\right]$$

EDIT : One can also directly call sympy and sk for a dictionary solution simpler to translate back in Sage:

sage: import sympy
sage: [{t._sage_():u[t]._sage_() for t in u.keys()} for u in sympy.solve(sympy.sympify(E),
....:  t, dict=True)]
[{t: u*sqrt((r^2*u^2 - a^2 - r^2)/(u^2 - 1))},
 {t: -u*sqrt((r^2*u^2 - a^2 - r^2)/(u^2 - 1))}]

EDIT 2: Along the same lines, one can use FriCAS to solve the same equation (with contorsions to to convert the result, again...):

sage: SG=fricas.solve(*[fricas(v) for v in [g-u, t]])
sage: [SG[w].lhs().sage()==SG[w].rhs().sage() for w in range(len(SG))]
[t == u*sqrt((r^2*u^2 - a^2 - r^2)/(u^2 - 1)),
 t == -u*sqrt((r^2*u^2 - a^2 - r^2)/(u^2 - 1))]

EDIT 3: Ditto for giac, minus the contorsions:

sage: giac.solve(giac(u-g), giac(t)).sage()
[sqrt(r^2*u^4 - a^2*u^2 - 2*r^2*u^2 + a^2 + r^2)*u/(u^2 - 1),
 -sqrt(r^2*u^4 - a^2*u^2 - 2*r^2*u^2 + a^2 + r^2)*u/(u^2 - 1)]

Mathematica gives the same solutions (again not automagically translatable to Sage):

sage: mathematica.Solve(E,t)
{{t -> -(Sqrt[-(a^2*u^2) - r^2*u^2 + r^2*u^4]/Sqrt[-1 + u^2])}, 
 {t -> Sqrt[-(a^2*u^2) - r^2*u^2 + r^2*u^4]/Sqrt[-1 + u^2]}}


2019-10-31 04:56:17 -0600 commented question How to solve this algebraic equation by SageMath (rather than by hand)

Homework ?

Hint: any solution of f(t)=g is also solution of f(t)^2=g^2 (but the converse is not true...).

2019-10-31 03:41:46 -0600 commented question How to find the coefficient of a boolean function with respect to some variable?

Please take the time to format your question to allow for easier reading (and possibly cut'n paste...).

2019-10-31 03:40:23 -0600 answered a question How to find the coefficient of a boolean function with respect to some variable?

Apparently, you want to treat the x as coefficients and the v as indeterminates. One way do do this is to create a ring of polynomials in x1, x2, x3overGF(2) :

sage: R1.<x1, x2, x3>=GF(2)[]
sage: R1
Multivariate Polynomial Ring in x1,

then a ring of polynomials in v1, v2, v3over the latter :

sage: R.<v1, v2, v3>=R1[]
sage: R
Multivariate Polynomial Ring in v1, v2, v3 over Multivariate Polynomial Ring in x1, x2, x3 over Finite Field of size 2

Define f pver this one: sage: f = 1+x1x2v1v2 + x3v1v2 + v1v3 +x1x2v3

and, lo !, it works as you intended:

sage: f.coefficient(v1*v2)
x1*x2 + x3

There are probably other ways to do this.


2019-10-30 09:37:07 -0600 answered a question 1.5 as a fraction

You've hit a well-known snag (more precisely a pair of well-known snags...).

> I know that 3÷2=1.5,

Mathematically, yes. But there's more to this in Sage:

First snag : Sage preparses your input and (silently) converts them in terms of Sage objects. For example:

sage: a=3
sage: type(a)
<type 'sage.rings.integer.Integer'>
sage: a.parent()
Integer Ring

In this case, Sage's preparser has read the string "3" as an element of your inut, concluded that it was a numerical integer constant and created a Sage object, element of the Integer ring (i. e $\left({\mathbb Z},\,+,\, .\right)$). The (Python) type of this object is the python representation of a class representing (some) sje objects, and the parent of this object is the Sage representation of this class.

These are different from Python integers which you can get by explicit conversion:

sage: pa=int(3)
sage: type(pa)
<type 'int'>

Such objects do not belong in the hierarchy of Sage objects:

sage: pa.parent()
AttributeError                            Traceback (most recent call last)
<ipython-input-11-7df6d5e7f9a4> in <module>()
----> 1 pa.parent()

AttributeError: 'int' object has no attribute 'parent'

The same is true of the preparsing of fractions:

> but how do you write 1.5 in fraction form.

Quite simply:

sage: b=3/2
sage: b
sage: type(b)
<type 'sage.rings.rational.Rational'>
sage: b.parent()
Rational Field

The latter is the Sage representation of the $\left({\mathbb Q},\,+,\, .\right)$ ring. And Sage's implementation of / for the class Integer somehow manages to compute the quotient of two integers in the Rational field (which is, of course, also a ring). In fact, it's a bit more complicated than that, for technical reasons, but this explanation is in essence correct.

Below the system of Sage classes and methods and their interrelation lies the notion of (mathematical) categories, which justifies this implementation. But this is a large subject, which, IIUC, is usually treated at postgrad level (at least un the US, Europeans may do things a bit differently...).

See the excellent book Computational Mathematics with SageMath for a (much better) introduction...

Of course, you can attempt the division of two Python integers. Which (here's the second snag) results in:

  • a (Python) integer if you're working in a Python 2-based Sage (current standard), where the division is the integer division :


sage: int(3)/int(2)
sage: type(int(3)/int(2))
<type 'int'>
  • a (Python) float if you're working in a Python 3-based Sage (soon-to-be standard), where the division is the float division:


sage: type(int(3)/int(2))
<class 'float'>

(One may note that Python 2 objects have a type, while Python 3 objects have a class ; neither have a parent; though...).

This behaviour results from a change of heart by Guido van Rossum between Python 2 and Python 3...

2019-10-29 09:06:16 -0600 answered a question how to use key as index in nested dictionary?

Alternative solution:

sage: D={1:{2:3,4:2},2:{}}
sage: D[1].update({5:'smile'})
sage: D
{1: {2: 3, 4: 2, 5: 'smile'}, 2: {}}

Possibly more readable...

2019-10-29 08:59:46 -0600 answered a question vector equation solve

Okay. On your head be it...

var("alpha, z")
F = vector([cos(alpha),sin(alpha),z])
G = vector([z,cos(alpha),sin(alpha)])
A = vector([0,0,0])
## Replace u==v by u-v (implicitlt ==0).

The system is redundant: the second equation is the sum of the first and the third, or, more swiftly,

sage: L
[-z + cos(alpha), -cos(alpha) + sin(alpha), z - sin(alpha)]

sympy offers some solutions:

sage: SS=solve(L,[z, alpha], algorithm="sympy"); SS
[{alpha: -3/4*pi, z: -1/2*sqrt(2)}, {alpha: 1/4*pi, z: 1/2*sqrt(2)}]

Easy check:

sage: [[e.subs(s) for e in L] for s in SS]
[[0, 0, 0], [0, 0, 0]]

But, are these solutions THE solution ?

Since the system is redundant, Sage's default solver (i. e. Maxima's) will choke (check it yourself). So let's try solve the second equation first:

sage: S1=L[1].solve(alpha); S1
[sin(alpha) == cos(alpha)]

Really ? One can do better (see the docs...)

sage: S1=L[1].solve(alpha, to_poly_solve=True); S1
[alpha == 1/4*pi + pi*z1]

Aha ! We have an infinity of solutions for alpha. What does it gives us for z ?

## Declare z1 as an integer (neither Sage nor Maxima will do that for you : minor pain in the a$$..)
sage: var("z1", domain="integer")
## Solve the first equation for `z`
sage: S0 = L[0].subs(S1).solve(z) ; S0
[z == 1/2*sqrt(2)*(-1)^z1]

We have two possible solutions for z. Check that this gives us valid solutions for the third equation:

sage: L[2].subs(S1).subs(S0)
1/2*sqrt(2)*(-1)^z1 - sin(1/4*pi + pi*z1)

Huh ? Here, it pays to have declared z1 as integer:

sage: L[2].subs(S1).subs(S0).simplify_trig()

Left to the reader as an exercise: alpha and z are bound by z1. Tabulate the results...

More advanced (requires a bit of familiarity with Sage's and Python's modules) : take a result given by Maxima's solver, and retrieve and declare (correctly) the variables created by the solver (useful also for the differential equations solve, etc...)

Brief conclusion of this short story : using a computer to compute solutions does not relieve you of the obligation to think about your problem and its solutions.


2019-10-29 01:47:48 -0600 answered a question In booleanpolynomialring how we can find coefficient?

Homework ?

Just a hint, for now: if I understand you correctly, you're trying to use v1, v2, v3 as the indeterminates of a (boolean) polynomial whose coefficients are themselves boolean polynomials. Try to implement that...