Is there a calculator with LaTeX-syntax? - latex

When I write math in LaTeX I often need to perform simple arithmetic on numbers in my LaTeX source, like 515.1544 + 454 = ???.
I usually copy-paste the LaTeX code into Google to get the result, but I still have to manually change the syntax, e.g.
\frac{154,7}{25} - (289 - \frac{1337}{42})
must be changed to
154,7/25 - (289 - 1337/42)
It seems trivial to write a program to do this for the most commonly used operations.
Is there a calculator which understand this syntax?
EDIT:
I know that doing this perfectly is impossible (because of the halting problem). Doing it for the simple cases I need is trivial. \frac, \cdot, \sqrt and a few other tags would do the trick. The program could just return an error for cases it does not understand.

WolframAlpha can take input in TeX form.
http://blog.wolframalpha.com/2010/09/30/talk-to-wolframalpha-in-tex/

The LaTeXCalc project is designed to do just that. It will read a TeX file and do the computations. For more information check out the home page at http://latexcalc.sourceforge.net/

The calc package allows you to do some calculations in source, but only within commands like \setcounter and \addtolength. As far as I can tell, this is not what you want.
If you already use sage, then the sagetex package is pretty awesome (if not, it's overkill). It allows you get nicely formatted output from input like this:
The square of
$\begin{pmatrix}
1 & 2 \\
3 & 4
\end{pmatrix}$
is \sage{matrix([[1, 2], [3,4]])^2}.
The prime factorization of the current page number is \sage{factor(\thepage)}

As Andy says, the answer is yes there is a calculator that can understand most latex formulas: Emacs.
Try the following steps (assuming vanilla emacs):
Open emacs
Open your .tex file (or activate latex-mode)
position the point somewhere between the two $$ or e.g. inside the begin/end environment of the formula (or even matrix).
use calc embedded mode for maximum awesomeness
So with point in the formula you gave above:
$\frac{154,7}{25} - (289 - \frac{1337}{42})$
press C-x * d to duplicate the formula in the line below and enter calc-embedded mode which should already have activated a latex variant of calc for you. Your buffer now looks like this:
$\frac{154,7}{25} - (289 - \frac{1337}{42})$
$\frac{-37651}{150}$`
Note that the fraction as already been transformed as far as possible. Doing the same again (C-x * d) and pressing c f to convert the fractional into a floating point number yields the following buffer:
$\frac{154,7}{25} - (289 - \frac{1337}{42})$
$\frac{-37651}{150}$
$-251.006666667$
I used C-x * d to duplicate the formula and then enter embedded mode in order to have the intermediate values, however there is also C-x * e which avoids the duplication and simply enters embedded mode for the current formula.
If you are interested you should really have a look at the info page for Emacs Calc - Embedded Mode. And in general the help for the Gnu Emaca Calculator together with the awesome interactive tutorial.

You can run an R function called Sweave on a (mostly TeX with some R) file that can replace R expressions with their results in Tex.
A tutorial can be found here: http://www.scribd.com/doc/6451985/Learning-to-Sweave-in-APA-Style

My calculator can do that. To get the formatted output, double-click the result formula and press ctrl+c to copy it.
It can do fairly advanced stuff too (differentiation, easy integrals (and not that easy ones)...).
https://calculator-algebra.org/
A sample computation:
https://calculator-algebra.org:8166/#%7B%22currentPage%22%3A%22calculator%22%2C%22calculatorInput%22%3A%22%5C%5Cfrac%7B1%2B2%7D%7B3%7D%3B%20d%2Fdx(arctan%20(2x%2B3))%22%2C%22monitoring%22%3A%22true%22%7D

There is a way to do what you want just not quite how you describe.
You can use the fp package (\usepackage[options]{fp}) the floating point package will do anything you want; solving equations, adding dividing and many more. Unfortunately it will not read the LaTeX math you instead have to do something a little different, the documentation is very poor so I'll give an example here.
for instance if you want to do (2x3)/5 you would type:
\FPmul\p{2}{3} % \p is the assignment of the operation 2x3
\FPupn\p{\p{} 7 round} % upn evaluates the assignment \p and rounds to 7dp
\FPdiv\q{\p}{5} % divides the assigned value p by 5 names result q
\FPupn\q{\q{} 4 round} % rounds the result to 4 decimal places and evaluates
$\frac{2\times3}{5}=\FPprint\q$ % This will print the result of the calculations in the math.
the FP commands are always ibvisible, only FPprint prints the result associated with it so your documents will not be messy, FP commands can be placed wherever you wish (not verb) as long as they are before the associated FPprint.

You could just paste it into symbolab which as a bonus has free step by step solutions. Also since symbolab uses mathquill it instantly formats your latex.

Considering that LaTeX itself is a Turing-complete markup language I strongly doubt you can build something like this that isn't built directly into LaTeX. Furthermore, LaTeX math matkup itself has next to no semantic meaning, it merely describes the visual appearance.
That being said, you can probably hack together something which recognizes a non-programmable subset of LaTeX math markup and spits out the result in the same way. If all you're interested in is simple arithmetics with fractions and integers (careful with decimal fractions, though, as they may appear as 3{,}141... in German texts :)) this shouldn't be too hard. But once you start with integrals, matrices, etc. I fear that LaTeX lacks expressiveness to accurately describe your intentions. It is a document preparation system, after all and thus not very suitable as input for computer algebra systems.
Side note: You can switch to Word which has—in its current version—a math markup language which is sufficiently LaTeX-like (by now it even supports LaTeX markup) and yet still Google-friendly for simpler terms:
With the free Microsoft Math add-in you can even let Word calculate expressions in-place:

There is none, because it is generally not possible.
LaTeX math mode markup is presentational markup and there are cases in which it does not provide enough information to calculate the expression.
That was one of the reasons MathML content markup was created and also why MathML is used in Mathematica. MathML actually is sort of two languages in one:
presentation markup
content markup
To accomplish what you are after you'll have to have MathML with comibned presentation and content markup (see MathML spec).
In my opinion your best bet is to use MathML (even if it is verbose) and convert to LaTeX when necessary. That said, I also like LaTeX syntax best and maybe what we need is a compact syntax for MathML (something similar in spirit to RelaxNG compact syntax).

For calculations with LaTeX you can use a CalcTeX package.
This package understand elements of LaTeX language and makes an calculations, for example your problem is avialble on
http://sg.bzip.pl/CalcTeX/examples/frac.tgz
or just please write
\noindent
For calculation please use following enviromentals
$515.1544 + 454$
or
\[ \frac{154.7}{25}-(289-\frac{1337}{42.})
\]
or
\begin{equation}
154.7/25-(289-1337/42.)
\end{equation}
For more info please visite project web site or contact author of this project.

For performing the math within your LaTeX itself, you might also look into the pgfmath package, which is more powerful and convenient than the calc package. You can find out how to use it from Part VI of The TikZ and PGF Packages Manual, which you can find here (version 2.10 currently): http://mirror.unl.edu/ctan/graphics/pgf/base/doc/generic/pgf/pgfmanual.pdf

Emacs calc-mode accepts latex-input. I use it daily. Press "d", followed by "L" to enter latex input mode. Press "'" to open a prompt where you can paste your tex.
Anyone saing it is not possible is wrong.

IIRC Mathematica can do it.

There is none, because it is generally not possible. LaTeX math mode
markup is presentational markup and there are cases in which it does
not provide enough information to calculate the expression.
You are right. LaTeX as it is does not provide enough info to make any calculations.Moreover, it does not represent any information to do it. But nobody prevents to wright in LaTeX format a text that contains such an information.
It is a difficult path, because you need to build a system of rules superimposed on what content ofthe text in Latex format needs to contain that it would be recognizable by your interpreter. And then convince the user that it is necessary to learn, etc. etc...
The easiest way to create a logical and intuitive calculator of mathematical expressions. And the expression is already possible to convert latex. It's almost like what you said. This is implemented in the program which I have pointed to. AnEasyCalc allows to type an expression as you type the plane text in any text editor. It checks, calculates and generate LateX string by its own then. Its very easy and rapid work. Just try and you will see that.

This is not exactly what you are asking for but it is a nice package
that you can include in a LaTeX document to do all kind of operations including arithmetic, calculus and even vectors and matrices:
The package name is "calculator"
http://mirror.unl.edu/ctan/macros/latex/contrib/calculator/calculator.pdf

The latex2sympy2 Python library can parse LaTeX math expressions.
from latex2sympy2 import latex2sympy
tex_str = r"""YOUR TEX MATH HERE"""
tex_str = r"\frac{9\pi}{\ln(12)}+22" # example TeX math
sympy_object = latex2sympy(tex_str)
evaluated_tex = float(sympy_object.evalf())
print(evaluated_tex)
This Python 3 code evaluates 9𝜋/ln(12)+22 (in its LaTeX from above) to 33.37842899841745.
The snippet above only handles basic algebraic simplification (math expressions without variables). Since the library converts LaTeX math to SymPy objects, the above code can easily be tweaked and extended to handle much more complicated LaTeX math (including solving derivatives, integrals, etc...).
The latex2sympy2 library can be installed via the pip command: pip install --user latex2sympy2

<>
try the AnEasyCalc program. It allows to get the latex formula very easy:
http://steamandwater.od.ua/AnEasyCalc/
:)

Related

Generating LaTeX Server Side

I'm trying to build a service that accepts some string with LaTeX formatting and then returns a string with the LaTeX bits as pngs, or whatever else.
So, the idea is:
client sends a request containing: the point is that $sum_{n=1}^5 f(x)$ is a good estimate
server sends back the string: the point is that FORMULAS_HERE is a good estimate
I really have no idea where to begin getting the LaTeX converted. Naively, I assume I would just parse out the LaTeX bits and then do something to get a png/jpeg/etc... and then insert that into the response.
Googling around really reveals minimal information.
Currently, my simple server is built on node, but that's not really important. I can change languages if there's some magic solution out there. I honestly wish I could magically transform LaTeX into unicode and have it be perfectly seamless.
Question: How do I handle LaTeX on the server side?
- The goal is to then spit it back to the client so the text can be inlined relatively naturally (i.e. I could text my buddy Hey, what if $\chi(n)$ was considered independently? and it would be received formatted on the other end without begin a weird big picture blob).
Any advice on just a direction or set of packages/technologies/etc.. would be useful here.
Prepare your latex document with math and convert it using the excellent open-source ImageMagick
pdflatex formula.tex
convert -density 300 formula.pdf -quality 90 formula.png
The convert command used above is one of the ImageMagick tools. See documentation and numerous online resources for many options. The software has versions for all major platforms.
The input latex file should be prepared so that there is no background, margins, etc. For discussion of how to do that, see this post, and the source for it. The example above ultimately comes from there.
This is one way to write the formula.tex file used above, from the linked source.
\ifdefined\formula
\else
\def\formula{E = m c^2}
\fi
\documentclass[border=2pt]{standalone}
\usepackage{amsmath}
\usepackage{varwidth}
\begin{document}
\begin{varwidth}{\linewidth}
\[ \formula \]
\end{varwidth}
\end{document}
There are other converters out there but you need not bother if you can use this.
I have to mention MathJax. It runs in a browser, via one-line JavaScript snippet. Should you ever migrate to a browser/mobile service this would be a perfect solution. Here is their one page tutorial.

Octave: saving figure with greek letters and subscripts

I'm currently trying to save a stress vs. strain curve using Octave. On this plot, I want to include text showing the equation for calculating engineering stress and engineering strain. Both of these require greek letters (\sigma and \epsilon respectively) as well as subscripts for the formulae.
Currently, using print with -deps, -dpng, or any other device, it creates a file, however the greek letters appear as the words "sigma" and "epsilon", and wherever I have a subscript, such as 0, it just appears as "_0". This looks very unprofessional.
Since I'm generating some 25 graphs, I don't want to have to go through and do a screenshot for each one. Does octave support saving the generated figure as displayed? I intend to use the generated files in a LaTeX document later (preferably as png so I can email them separately too).
I've also tried changing the "graphics_toolkit" option between fltk and gnuplot however it doesn't seem to help.
Attached to this post is a screenshot of the desired results and the actual results.
I am currently "not allowed" to post images, so I'll link them:
http://i.imgur.com/Tjt5Ecn.png (screenshot, desired result) and http://i.imgur.com/SP3hekd.png (directly saved, actual result)
Does anyone know a good way to print a figure from Octave which includes greek characters and subscripts in the titles?
Since you plan to use your graph in a Latex document, generating the graphs with -depslatex and converting them to pdf is a good idea . (Results look slightly better than direct -dpdflatex).
With -depslatex, you can include Latex code in your figures that will be written to a separate tex file.
Note that you need to use double backslashes \\ to export a single backslash.
graphics_toolkit("gnuplot");
...
legend("$\\varepsilon$");
print(sprintf("graph%s_%d.eps", name, type), '-depslatex', '-S200,270', '-F:9');
system(sprintf("epstopdf graph%s_%d.eps", name, type));
On the Latex side, you then \input the tex file generated by Octave. On the plus side, since you need 25 graphs, you can automatize this process on both sides Octave and Latex.
\newcommand{\mygraph}[1]{%
\graphicspath{{./figures/}}
\resizebox{0.495\linewidth}{!}{\relscale{1.0}\small%
\input{./figures/#1.tex}
}%
}
\mygraph{graph1_1}
Here, a Latex command \mygraph is defined to scale and include a figure located in a subfolder.
(I am using Octave 4.0.0 with gnuplot 4.4 on Ubuntu 12)

How to convert Latex formula to C/C++ code?

I need to convert a math formula written in the Latex style to the function of a C/C++ code.
For example:
y = sin(x)^2 would become something like
double y = sin(x) * sin(x);
or
double y = pow(sin(x), 2);
where x is a variable defined somewhere before.
I mean that it should convert the latex formula to the C/C++ syntax. So that if there is a function y = G(x, y)^F(x) it doesn't matter what is G(x,y) and F(x),
it is a problem of the programmer to define it. It will just generate
double y = pow(G(x, y), F(x));
When the formula is too complicated it will take some time to make include it in the C/C++ formula. Is there any way to do this conversion?
Emacs' built-in calculator calc-mode can do this (and much more). Your examples can be converted like this:
Put the formula in some emacs buffer
$ y = sin(x)^2 $
With the cursor in the formula, activate calc-embedded mode
M-x calc-embedded
Switch the display language to C:
M-x calc-c-language
There you are:
$ y == pow(sin(x), 2) $
Note that it interprets the '=' sign in latex as an equality, which results in '==' for C. The latex equivalent to Cs assignment operator '=' would be '\gets'.
More on this topic on Turong's blog
I know the question is too old, but I'll just add a reply anyway as a think it might help someone else later. The question popped up a lot for me in my searches.
I'm working on a tool that does something similar, in a public git repo
You'll have to put some artificial limitations on your latex input, that's out of question.
Currently the tool I wrote only supports mul, div, add, sub, sqrt, pow, frac and sum as those are the only set of operations I need to handle, and the imposed limitations can be a bit loose by providing a preprocessor (see preproc.l for an [maybe not-so-good] example) that would clean away the raw latex input.
A mathematical equation, such as the ones in LaTeX, and a C expression are not interchangeable. The former states a relation between two terms, the latter defines an entity that can be evaluated, unambiguously yielding one value. a = b in C means 'take the value in variable b and store it in variable a', wheres in Math, it means 'in the current context, a and b are equal'. The first describes a computation process, the second describes a static fact. Consequently, the Math equation can be reversed: a = b is equivalent to b = a, but doing the same to the C equation yields something quite different.
To make matters worse, LaTeX formulae only contain the information needed to render the equations; often, this is not enough to capture their meaning.
Of course some LaTeX formulae, like your example, can be converted into C computations, but many others cannot, so any automated way of doing so would only make limited sense.
I'm not sure there is a simple answer, because mathematical formulaes (in LaTeX documents) are actually ambiguous, so to automate their translation to some code requires automating their understanding.
And the MathML standard has, IIRC, two forms representing formulaes (one for displaying, another for computing) and there is some reason for that.

Tools for converting LaTeX equations to Content MathML or OpenMath?

Do you know any open source tools or libraries (preferably Java, but that's not a strict requirement) in the GNU/Linux world that convert mathematical equations in LaTeX syntax to Content MathML or OpenMath?
I need to convert tons of equations in batch mode, so I'm not looking for interactive apps.
EDIT My focus is on the equations' semantics, so I cannot use Presentation MathML (unless there's a converter from Presentation MathML to Content MathML).
Thanks in advance!
This might be what you are looking for: SnuggleTeX
From the site:
SnuggleTeX is a 100% Java library for converting (a reasonable subset of) LaTeX into XHTML + MathML.
SnuggleTeX can attempt to convert input LaTeX to Content MathML by first creating Enhanced Presentation MathML and then processing that. In many ways, this part of the process is relatively simple since most of the semantic structure has already been inferred (though might not necessarily make any sense).
You can also use an online equation editor WIRIS editor which is able to import MathML/Latex and export to MathML/Latex
Have a look over here, where you can find a perl version.
You may want to have a look at LaTeXML. It converts LaTeX to various XML formats, including OpenMath and content MathML.
But be warned, like all other tools, the conversion from (presentation-oriented) LaTeX to content markup (as in OpenMath and MathML) is heuristic. In particular, in ambiguous situations (e.g. $f(a+b)$, which can mean $f$ applied to $(a+b)$ or $f$ times $(a+b)$) LaTeXML chooses one (usually times).
There are two ways out:
1) use content markup already in the LaTeX source (see http://trac.kwarc.info/sTeX)
2) use a better post-processor for LaTeXML is working on this

How to start math formulae in new line if bad boxed in latex?

What sort of code should I put in preamble, such that every math fomula (in dolar signs) that is too long to fit in line width (a.k.a. produces Bad Box) start in new line (like putting // before equation) ? Or is it impossible to detect and prevent Bad Box in compiling ?
You could use \sloppy or \sloppypar, but that will reduce the quality of the line breaks.
Take a look here.
Are you talking about inline math or TeX-style $$? In the first case: think about putting it in its own environment, long inline math isn't a good idea. In the second case, start using align (or the appropriate environment) and place those breaks yourself. Or use breqn, it will do it automatically.
In case it's inline and you want it to stay inline: consider rewriting your sentences, as usual with bad boxes. And consider using microtype if you're building to pdf, it will enhance the flexibility of the fonts, hence, more possibilities for line breaking.
I don't have an actual solution for line breaks in inline math, I usually resort to these tricks. Maybe someone with a better insignt in inline math can help you with that :).

Resources