Alex Alex
Alex Alex

Reputation: 261

Convert R yacas equation to LaTeX without solving it

I want to show step-by-step calculations that were made using 'TeXForm' in Ryacas.
To do that I must be able to obtain LaTeX from given equation. Issue is that yacas automatically solves them before converting to LaTeX form. If I try to apply 'TeXForm' on equation, I get simplified version of it. For example:

exp1<-'D(x)Sin(x^2+y^2)+D(y)Sin(x^2+y^2)'
TeXForm(exp1)

I got:

"$2 x \cos \left( x ^{2} + y ^{2}\right)  + 2 y \cos \left( x ^{2} + y ^{2}\right) $";

I tried to get non-simplified version:

 yacas('TeXForm(exp1)')

I got:

"$\mathrm{ exp1 }$";

I also tried:

yacas('D(x)Sin(x^2+y^2)+D(y)Sin(x^2+y^2)')

It didn`t work either.
How to get non-simplified LaTeX formula with all derivatives?

Upvotes: 2

Views: 304

Answers (3)

MDAions
MDAions

Reputation: 1

Some functions are ok :

for example :

TeXForm(Hold(Integrate(a) (a^2+5)) ) 

give :

$\int \left( a ^{2} + 5\right)  da$

but not all functions... this one don't match :

TeXForm(substitute("D(x) sin(x+y)"))

but even :

TeXForm(Hold(D(x)Sin(x^2+y^2)+D(y)Sin(x^2+y^2))) 

give :

$2 x \cos \left( x ^{2} + y ^{2}\right)  + \frac{\partial}{\partial x}\left( 2 y \cos \left( x ^{2} + y ^{2}\right) \right) $

It's in the doc : "https://yacas.readthedocs.io/en/latest/reference_manual/controlflow.html#Hold"

Upvotes: 0

haakonstorm
haakonstorm

Reputation: 69

To prevent yacas to evaluate your expression, you can wrap your expression with Hold().

E.g: You have an expression "Limit(x,0) Sqrt(x) * Sin(1/x)", and you want yacas to parse this and convert it to the LaTeX format, without evaluating the expression.

Expand your expression like this:

s <- "Limit(x,0) Sqrt(x) * Sin(1/x)" 
expanded_yacas_charstr <- paste("Hold(", s, ") == ", s, sep = "")

I made a function to use this in Rmarkdown documents, returning the input function along with its result, as a combined LaTeX result. This might be useful to you:

```{r, results="asis", echo=FALSE}

  kalk <- function(s) {
  library("Ryacas")

  # Expand yacas expression
  # e.g. 
  #       Limit(x,0) Sqrt(x) 
  # is expanded to 
  #       Hold("Limit(x,0) Sqrt(x) == )" Limit(x,0) Sqrt(x)
  #
  # This prevents yacas to evaluate the text inside Hold()

  expanded_yacas_charstr <- paste("Hold(", s, ") == ", s, sep = "")

  s <- as.character(yacas(verbose=false,
                          TeXForm(expanded_yacas_charstr),
                          retclass = "unquote"))

  return(paste("$$ ", substr(s, 2, nchar(s)), "$", sep = ""))
}

# use cat() to make sure "[1]"" output is removed
cat(kalk("Limit(x,0) Sqrt(x) * Sin(1/x)"))
``` 

Upvotes: 1

Alex Alex
Alex Alex

Reputation: 261

I found that TeXForm(deparse(x^2+x^2)) gives right result, but that doesn't work with derivatives.
For derivatives: TeXForm(substitute("D(x) sin(x+y)")).

Upvotes: 0

Related Questions