Best practice for printing and evaluating formulas with the minimal codingHow to properly smuggle (with or even without TikZ)?Best practice for quoting a websiteBest practice: LaTeX constants for possibly changing repeatedly used symbolBest practice for index construction — recommendations and referencesIs removing ensuremath the best practice?Best Practice for creating user-defined command namesBest practice for typesetting quantifiers?Best Practice (Packages) for a Standard Technical Article With Math and FiguresBest practice for biblatex, biber, utf8 filesBest Practice: Package for Mathematical Documents - amsmath and Beyondbest practice for consistent text snippets

Are black holes spherical during merger?

NIntegrate doesn't evaluate

First Match - awk

Is "cool" appropriate or offensive to use in IMs?

Is the Indo-European language family made up?

Can a British citizen living in France vote in both France and Britain in the European Elections?

How to politely tell someone they did not hit "reply to all" in an email?

What was the idiom for something that we take without a doubt?

Count rotary dial pulses in a phone number (including letters)

How should I introduce map drawing to my players?

Is there an online tool which supports shared writing?

Why aren't space telescopes put in GEO?

Why didn't Thanos use the Time Stone to stop the Avengers' plan?

My employer faked my resume to acquire projects

Pirate democracy at its finest

USPS Back Room - Trespassing?

Apt - strange requests to d16r8ew072anqo.cloudfront.net:80

How to respond to upset student?

Popcorn is the only acceptable snack to consume while watching a movie

Did this character show any indication of wanting to rule before S8E6?

Does this strict reading of the rules allow both Extra Attack and the Thirsting Blade warlock invocation to be used together?

Can a person survive on blood in place of water?

Defining the standard model of PA so that a space alien could understand

Count Even Digits In Number



Best practice for printing and evaluating formulas with the minimal coding


How to properly smuggle (with or even without TikZ)?Best practice for quoting a websiteBest practice: LaTeX constants for possibly changing repeatedly used symbolBest practice for index construction — recommendations and referencesIs removing ensuremath the best practice?Best Practice for creating user-defined command namesBest practice for typesetting quantifiers?Best Practice (Packages) for a Standard Technical Article With Math and FiguresBest practice for biblatex, biber, utf8 filesBest Practice: Package for Mathematical Documents - amsmath and Beyondbest practice for consistent text snippets













7















Can the following MWE be reduced by creating a command that can accept a formula then print and evaluate it without the need to write it twice in two different forms for both evaluating and printing as shown below?



documentclass[border=5mm]standalone
usepackagepgf,mathtools,siunitx

begindocument

newcommandtoprintfrac-4+sqrt4^2-4*1*32
newcommandtoevaluate(-4+sqrt(4^2-4*1*3))/2

pgfmathparsetoevaluate

The first root is evaluated by $x_1 = toprint = SIpgfmathresultcm $

enddocument


enter image description here










share|improve this question


























    7















    Can the following MWE be reduced by creating a command that can accept a formula then print and evaluate it without the need to write it twice in two different forms for both evaluating and printing as shown below?



    documentclass[border=5mm]standalone
    usepackagepgf,mathtools,siunitx

    begindocument

    newcommandtoprintfrac-4+sqrt4^2-4*1*32
    newcommandtoevaluate(-4+sqrt(4^2-4*1*3))/2

    pgfmathparsetoevaluate

    The first root is evaluated by $x_1 = toprint = SIpgfmathresultcm $

    enddocument


    enter image description here










    share|improve this question
























      7












      7








      7


      1






      Can the following MWE be reduced by creating a command that can accept a formula then print and evaluate it without the need to write it twice in two different forms for both evaluating and printing as shown below?



      documentclass[border=5mm]standalone
      usepackagepgf,mathtools,siunitx

      begindocument

      newcommandtoprintfrac-4+sqrt4^2-4*1*32
      newcommandtoevaluate(-4+sqrt(4^2-4*1*3))/2

      pgfmathparsetoevaluate

      The first root is evaluated by $x_1 = toprint = SIpgfmathresultcm $

      enddocument


      enter image description here










      share|improve this question














      Can the following MWE be reduced by creating a command that can accept a formula then print and evaluate it without the need to write it twice in two different forms for both evaluating and printing as shown below?



      documentclass[border=5mm]standalone
      usepackagepgf,mathtools,siunitx

      begindocument

      newcommandtoprintfrac-4+sqrt4^2-4*1*32
      newcommandtoevaluate(-4+sqrt(4^2-4*1*3))/2

      pgfmathparsetoevaluate

      The first root is evaluated by $x_1 = toprint = SIpgfmathresultcm $

      enddocument


      enter image description here







      math-mode best-practices pgfmath






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked May 18 at 20:55









      DiaaDiaa

      3,00311858




      3,00311858




















          2 Answers
          2






          active

          oldest

          votes


















          9














          AFAIK there is no such function available but I may be wrong. You could write your own parser that locally redefines the macros that print stuff to macros that wraps stuff in the respective functions. In the code below, I do that for frac and sqrt. This works in this case, also because you were kind enough to explicitly spell out multiplications and even used * for them. Clearly, this "parser" is fragile, but if you really feel it is worthwhile you may add other functions like sin and so on.



          documentclass[border=5mm]standalone
          usepackagepgf,mathtools,siunitx

          begindocument

          newcommandtoprintfrac-4+sqrt4^2-4*1*32
          %newcommandtoevaluate(-4+sqrt(4^2-4*1*3))/2
          newcommandDiaaParse[1]begingroupdeffrac##1##2((##1)/(##2))%
          defsqrt##1sqrt(##1)%
          edefret#1%
          pgfmathparseretpgfmathprintnumberpgfmathresult%
          endgroup

          %pgfmathparsetoevaluate

          The first root is evaluated by $x_1 = toprint = DiaaParsetoprint$

          enddocument


          enter image description here



          This version does not work with SI, also because I didn't understand where the units cm come from, but this could be changed.



          If you want the parser just to parse and to store the result in pgfmathresult, you could use



          documentclass[border=5mm]standalone
          usepackagepgf,mathtools,siunitx

          begindocument

          newcommandtoprintfrac-4+sqrt4^2-4times1times 32
          newcommandDiaaParse[1]begingroupdeffrac##1##2((##1)/(##2))%
          defsqrt##1sqrt(##1)%
          defcdot*%
          deftimes*%
          defexp##1exp(##1)%
          deflog##1log(##1)%
          defln##1ln(##1)%
          defarcsin##1asin(##1)%
          defcot##1cot(##1)%
          defsin##1sin(##1)%
          defsinh##1sinh(##1)%
          defarccos##1acos(##1)%
          defcot##1cot(##1)%
          defcos##1cos(##1)%
          defarctan##1atan(##1)%
          defcot##1cot(##1)%
          deftan##1tan(##1)%
          deftanh##1tanh(##1)%
          defarccot##1acot(##1)%
          defcot##1cot(##1)%
          defcot##1cot(##1)%
          edefret#1%
          pgfmathparseret%
          pgfmathsmugglepgfmathresult%
          endgroup


          The first root is evaluated by $x_1 = toprint =DiaaParsetoprint
          SIpgfmathresultcm$

          enddocument


          enter image description here



          As you see, this does work with SI and so on, simply because it wraps the additional parsing around pgfmathparse. This also defines the replacement rules for other commands, but I stress it is fragile. Please note that this requires a rather recent version of pgf (3.1.1 or higher, I think) which has pgfmathsmuggle in it. For older versions, you have to use other smuggling techniques, see the answers of this question for possible ways.



          Overall this does something of the sort you are suggesting, but I stress it is fragile. What if a user wants to compute, say, log_7 29? Yes, one could extend the parser to deal with that as well, but this will be more effort. And then the next user wants sqrt[3]19. Also possible, but more efforts. And how about log_10 3frac14, how would the parser know that this is log(13/4)/log(7)? Of course, if you use external programs, you can avoid duplication, e.g. Mathematica has TeXForm to convert the result of some module to not-so-nice but most times working (La)TeX code.






          share|improve this answer

























          • Could you please suggest how to deal with the multiplication in the form of times instead of *?

            – Diaa
            May 19 at 1:04






          • 1





            @Diaa You just have to add defcdot*%, which I added in the second example.

            – marmot
            May 19 at 2:51






          • 1





            @Diaa This works the same for times: deftimes*%.

            – marmot
            May 19 at 3:25






          • 3





            @Diaa I recommend tikzmarmots. It does not produce precisely the same output, but is much more entertaining. ;-) More seriously, I can see that why folks are reluctant to write such a package. It will be (almost) inevitably fragile. So you spend 10 minutes on writing the core functions and 5 month on making it more robust. It is almost trivial to add the functions of section 94.3 Syntax for Mathematical Expressions: Functions of the pgfmanual 3.1.3 to the above parser but very hard to cope with all the ways users may typeset their expressions.

            – marmot
            May 19 at 4:14






          • 1





            @Diaa If I would have to guess, then I'd think that the author/maintainer of siunitx will have the best chances of accomplishing this. siunitx does already a lot of related things and its maintainer presumably has a very good idea of what can go wrong.

            – marmot
            May 19 at 19:55


















          2














          Some years ago, I had the same problem.



          Since writing a robust parser is not a trivial exercise, I decided to not try it in TeX, but use Python (version 3.6 or later) instead.



          The result was the TeXcalc module.



          The input looks like this:



          from texcalc import Calculation

          c = Calculation()
          c.add('rho_f', '1.62', 'g/cm^3', 'Fiber density')
          c.add('rho_r', '1.2', 'g/cm^3', "Resin density")
          c.add('v_f', '0.3', '-', 'Fiber volume fraction')
          c.add('W_f', '450', 'g/m^2', "Area weight fibers", fmt=".0f")
          c.add('t_f', 'W_f/(10000*rho_f)*10', 'mm')
          c.add('t', 't_f/v_f', 'mm', "Laminate thickness")
          c.add('t_r', 't-t_f', 'mm')
          c.add('W_r', 't_f/10*(10000*rho_r)', 'g/m^2', "Area weight resin", fmt=".0f")
          print(c)


          It outputs an align* environment (from the amsmath package) and uses siunitx to typeset the units. After processing with LaTeX, the output looks like this.
          TexCalc example




          Adapted to the MWE on request



          The following are the contents of mwe.py



          from texcalc import Calculation

          c = Calculation()
          c.add('b', 4)
          c.add('a', 1)
          c.add('c', 3)
          c.add('x1', '(-b+sqrt(b**2-4*a*c))/2', 'cm', 'first root')
          c.add('x2', '(-b-sqrt(b**2-4*a*c))/2', 'cm', 'second root')
          print(c)


          Run this as python3 mwe.py > foo.tex



          This is mwe.tex:



          documentclass[preview=true]standalone
          usepackageamsmath,siunitx

          begindocument
          inputfoo.tex
          enddocument


          Run this with pdflatex mwe.tex.



          This results in:
          MWE image



          The goal of TeXcalc is to clarify complicated calculations that have multiple steps, as shown in the first example. This to make it easier for others to follow.



          So it cannot exactly match your MWE, since it doesn't produce in-line math. Although in this case, you could extract the necessary data from foo.tex.






          share|improve this answer




















          • 1





            Your answer looks interesting. Could you please adapt it to my MWE?

            – Diaa
            May 19 at 10:18






          • 1





            @Diaa: See updated answer.

            – Roland Smith
            May 19 at 17:23











          Your Answer








          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "85"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2ftex.stackexchange.com%2fquestions%2f491540%2fbest-practice-for-printing-and-evaluating-formulas-with-the-minimal-coding%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          2 Answers
          2






          active

          oldest

          votes








          2 Answers
          2






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          9














          AFAIK there is no such function available but I may be wrong. You could write your own parser that locally redefines the macros that print stuff to macros that wraps stuff in the respective functions. In the code below, I do that for frac and sqrt. This works in this case, also because you were kind enough to explicitly spell out multiplications and even used * for them. Clearly, this "parser" is fragile, but if you really feel it is worthwhile you may add other functions like sin and so on.



          documentclass[border=5mm]standalone
          usepackagepgf,mathtools,siunitx

          begindocument

          newcommandtoprintfrac-4+sqrt4^2-4*1*32
          %newcommandtoevaluate(-4+sqrt(4^2-4*1*3))/2
          newcommandDiaaParse[1]begingroupdeffrac##1##2((##1)/(##2))%
          defsqrt##1sqrt(##1)%
          edefret#1%
          pgfmathparseretpgfmathprintnumberpgfmathresult%
          endgroup

          %pgfmathparsetoevaluate

          The first root is evaluated by $x_1 = toprint = DiaaParsetoprint$

          enddocument


          enter image description here



          This version does not work with SI, also because I didn't understand where the units cm come from, but this could be changed.



          If you want the parser just to parse and to store the result in pgfmathresult, you could use



          documentclass[border=5mm]standalone
          usepackagepgf,mathtools,siunitx

          begindocument

          newcommandtoprintfrac-4+sqrt4^2-4times1times 32
          newcommandDiaaParse[1]begingroupdeffrac##1##2((##1)/(##2))%
          defsqrt##1sqrt(##1)%
          defcdot*%
          deftimes*%
          defexp##1exp(##1)%
          deflog##1log(##1)%
          defln##1ln(##1)%
          defarcsin##1asin(##1)%
          defcot##1cot(##1)%
          defsin##1sin(##1)%
          defsinh##1sinh(##1)%
          defarccos##1acos(##1)%
          defcot##1cot(##1)%
          defcos##1cos(##1)%
          defarctan##1atan(##1)%
          defcot##1cot(##1)%
          deftan##1tan(##1)%
          deftanh##1tanh(##1)%
          defarccot##1acot(##1)%
          defcot##1cot(##1)%
          defcot##1cot(##1)%
          edefret#1%
          pgfmathparseret%
          pgfmathsmugglepgfmathresult%
          endgroup


          The first root is evaluated by $x_1 = toprint =DiaaParsetoprint
          SIpgfmathresultcm$

          enddocument


          enter image description here



          As you see, this does work with SI and so on, simply because it wraps the additional parsing around pgfmathparse. This also defines the replacement rules for other commands, but I stress it is fragile. Please note that this requires a rather recent version of pgf (3.1.1 or higher, I think) which has pgfmathsmuggle in it. For older versions, you have to use other smuggling techniques, see the answers of this question for possible ways.



          Overall this does something of the sort you are suggesting, but I stress it is fragile. What if a user wants to compute, say, log_7 29? Yes, one could extend the parser to deal with that as well, but this will be more effort. And then the next user wants sqrt[3]19. Also possible, but more efforts. And how about log_10 3frac14, how would the parser know that this is log(13/4)/log(7)? Of course, if you use external programs, you can avoid duplication, e.g. Mathematica has TeXForm to convert the result of some module to not-so-nice but most times working (La)TeX code.






          share|improve this answer

























          • Could you please suggest how to deal with the multiplication in the form of times instead of *?

            – Diaa
            May 19 at 1:04






          • 1





            @Diaa You just have to add defcdot*%, which I added in the second example.

            – marmot
            May 19 at 2:51






          • 1





            @Diaa This works the same for times: deftimes*%.

            – marmot
            May 19 at 3:25






          • 3





            @Diaa I recommend tikzmarmots. It does not produce precisely the same output, but is much more entertaining. ;-) More seriously, I can see that why folks are reluctant to write such a package. It will be (almost) inevitably fragile. So you spend 10 minutes on writing the core functions and 5 month on making it more robust. It is almost trivial to add the functions of section 94.3 Syntax for Mathematical Expressions: Functions of the pgfmanual 3.1.3 to the above parser but very hard to cope with all the ways users may typeset their expressions.

            – marmot
            May 19 at 4:14






          • 1





            @Diaa If I would have to guess, then I'd think that the author/maintainer of siunitx will have the best chances of accomplishing this. siunitx does already a lot of related things and its maintainer presumably has a very good idea of what can go wrong.

            – marmot
            May 19 at 19:55















          9














          AFAIK there is no such function available but I may be wrong. You could write your own parser that locally redefines the macros that print stuff to macros that wraps stuff in the respective functions. In the code below, I do that for frac and sqrt. This works in this case, also because you were kind enough to explicitly spell out multiplications and even used * for them. Clearly, this "parser" is fragile, but if you really feel it is worthwhile you may add other functions like sin and so on.



          documentclass[border=5mm]standalone
          usepackagepgf,mathtools,siunitx

          begindocument

          newcommandtoprintfrac-4+sqrt4^2-4*1*32
          %newcommandtoevaluate(-4+sqrt(4^2-4*1*3))/2
          newcommandDiaaParse[1]begingroupdeffrac##1##2((##1)/(##2))%
          defsqrt##1sqrt(##1)%
          edefret#1%
          pgfmathparseretpgfmathprintnumberpgfmathresult%
          endgroup

          %pgfmathparsetoevaluate

          The first root is evaluated by $x_1 = toprint = DiaaParsetoprint$

          enddocument


          enter image description here



          This version does not work with SI, also because I didn't understand where the units cm come from, but this could be changed.



          If you want the parser just to parse and to store the result in pgfmathresult, you could use



          documentclass[border=5mm]standalone
          usepackagepgf,mathtools,siunitx

          begindocument

          newcommandtoprintfrac-4+sqrt4^2-4times1times 32
          newcommandDiaaParse[1]begingroupdeffrac##1##2((##1)/(##2))%
          defsqrt##1sqrt(##1)%
          defcdot*%
          deftimes*%
          defexp##1exp(##1)%
          deflog##1log(##1)%
          defln##1ln(##1)%
          defarcsin##1asin(##1)%
          defcot##1cot(##1)%
          defsin##1sin(##1)%
          defsinh##1sinh(##1)%
          defarccos##1acos(##1)%
          defcot##1cot(##1)%
          defcos##1cos(##1)%
          defarctan##1atan(##1)%
          defcot##1cot(##1)%
          deftan##1tan(##1)%
          deftanh##1tanh(##1)%
          defarccot##1acot(##1)%
          defcot##1cot(##1)%
          defcot##1cot(##1)%
          edefret#1%
          pgfmathparseret%
          pgfmathsmugglepgfmathresult%
          endgroup


          The first root is evaluated by $x_1 = toprint =DiaaParsetoprint
          SIpgfmathresultcm$

          enddocument


          enter image description here



          As you see, this does work with SI and so on, simply because it wraps the additional parsing around pgfmathparse. This also defines the replacement rules for other commands, but I stress it is fragile. Please note that this requires a rather recent version of pgf (3.1.1 or higher, I think) which has pgfmathsmuggle in it. For older versions, you have to use other smuggling techniques, see the answers of this question for possible ways.



          Overall this does something of the sort you are suggesting, but I stress it is fragile. What if a user wants to compute, say, log_7 29? Yes, one could extend the parser to deal with that as well, but this will be more effort. And then the next user wants sqrt[3]19. Also possible, but more efforts. And how about log_10 3frac14, how would the parser know that this is log(13/4)/log(7)? Of course, if you use external programs, you can avoid duplication, e.g. Mathematica has TeXForm to convert the result of some module to not-so-nice but most times working (La)TeX code.






          share|improve this answer

























          • Could you please suggest how to deal with the multiplication in the form of times instead of *?

            – Diaa
            May 19 at 1:04






          • 1





            @Diaa You just have to add defcdot*%, which I added in the second example.

            – marmot
            May 19 at 2:51






          • 1





            @Diaa This works the same for times: deftimes*%.

            – marmot
            May 19 at 3:25






          • 3





            @Diaa I recommend tikzmarmots. It does not produce precisely the same output, but is much more entertaining. ;-) More seriously, I can see that why folks are reluctant to write such a package. It will be (almost) inevitably fragile. So you spend 10 minutes on writing the core functions and 5 month on making it more robust. It is almost trivial to add the functions of section 94.3 Syntax for Mathematical Expressions: Functions of the pgfmanual 3.1.3 to the above parser but very hard to cope with all the ways users may typeset their expressions.

            – marmot
            May 19 at 4:14






          • 1





            @Diaa If I would have to guess, then I'd think that the author/maintainer of siunitx will have the best chances of accomplishing this. siunitx does already a lot of related things and its maintainer presumably has a very good idea of what can go wrong.

            – marmot
            May 19 at 19:55













          9












          9








          9







          AFAIK there is no such function available but I may be wrong. You could write your own parser that locally redefines the macros that print stuff to macros that wraps stuff in the respective functions. In the code below, I do that for frac and sqrt. This works in this case, also because you were kind enough to explicitly spell out multiplications and even used * for them. Clearly, this "parser" is fragile, but if you really feel it is worthwhile you may add other functions like sin and so on.



          documentclass[border=5mm]standalone
          usepackagepgf,mathtools,siunitx

          begindocument

          newcommandtoprintfrac-4+sqrt4^2-4*1*32
          %newcommandtoevaluate(-4+sqrt(4^2-4*1*3))/2
          newcommandDiaaParse[1]begingroupdeffrac##1##2((##1)/(##2))%
          defsqrt##1sqrt(##1)%
          edefret#1%
          pgfmathparseretpgfmathprintnumberpgfmathresult%
          endgroup

          %pgfmathparsetoevaluate

          The first root is evaluated by $x_1 = toprint = DiaaParsetoprint$

          enddocument


          enter image description here



          This version does not work with SI, also because I didn't understand where the units cm come from, but this could be changed.



          If you want the parser just to parse and to store the result in pgfmathresult, you could use



          documentclass[border=5mm]standalone
          usepackagepgf,mathtools,siunitx

          begindocument

          newcommandtoprintfrac-4+sqrt4^2-4times1times 32
          newcommandDiaaParse[1]begingroupdeffrac##1##2((##1)/(##2))%
          defsqrt##1sqrt(##1)%
          defcdot*%
          deftimes*%
          defexp##1exp(##1)%
          deflog##1log(##1)%
          defln##1ln(##1)%
          defarcsin##1asin(##1)%
          defcot##1cot(##1)%
          defsin##1sin(##1)%
          defsinh##1sinh(##1)%
          defarccos##1acos(##1)%
          defcot##1cot(##1)%
          defcos##1cos(##1)%
          defarctan##1atan(##1)%
          defcot##1cot(##1)%
          deftan##1tan(##1)%
          deftanh##1tanh(##1)%
          defarccot##1acot(##1)%
          defcot##1cot(##1)%
          defcot##1cot(##1)%
          edefret#1%
          pgfmathparseret%
          pgfmathsmugglepgfmathresult%
          endgroup


          The first root is evaluated by $x_1 = toprint =DiaaParsetoprint
          SIpgfmathresultcm$

          enddocument


          enter image description here



          As you see, this does work with SI and so on, simply because it wraps the additional parsing around pgfmathparse. This also defines the replacement rules for other commands, but I stress it is fragile. Please note that this requires a rather recent version of pgf (3.1.1 or higher, I think) which has pgfmathsmuggle in it. For older versions, you have to use other smuggling techniques, see the answers of this question for possible ways.



          Overall this does something of the sort you are suggesting, but I stress it is fragile. What if a user wants to compute, say, log_7 29? Yes, one could extend the parser to deal with that as well, but this will be more effort. And then the next user wants sqrt[3]19. Also possible, but more efforts. And how about log_10 3frac14, how would the parser know that this is log(13/4)/log(7)? Of course, if you use external programs, you can avoid duplication, e.g. Mathematica has TeXForm to convert the result of some module to not-so-nice but most times working (La)TeX code.






          share|improve this answer















          AFAIK there is no such function available but I may be wrong. You could write your own parser that locally redefines the macros that print stuff to macros that wraps stuff in the respective functions. In the code below, I do that for frac and sqrt. This works in this case, also because you were kind enough to explicitly spell out multiplications and even used * for them. Clearly, this "parser" is fragile, but if you really feel it is worthwhile you may add other functions like sin and so on.



          documentclass[border=5mm]standalone
          usepackagepgf,mathtools,siunitx

          begindocument

          newcommandtoprintfrac-4+sqrt4^2-4*1*32
          %newcommandtoevaluate(-4+sqrt(4^2-4*1*3))/2
          newcommandDiaaParse[1]begingroupdeffrac##1##2((##1)/(##2))%
          defsqrt##1sqrt(##1)%
          edefret#1%
          pgfmathparseretpgfmathprintnumberpgfmathresult%
          endgroup

          %pgfmathparsetoevaluate

          The first root is evaluated by $x_1 = toprint = DiaaParsetoprint$

          enddocument


          enter image description here



          This version does not work with SI, also because I didn't understand where the units cm come from, but this could be changed.



          If you want the parser just to parse and to store the result in pgfmathresult, you could use



          documentclass[border=5mm]standalone
          usepackagepgf,mathtools,siunitx

          begindocument

          newcommandtoprintfrac-4+sqrt4^2-4times1times 32
          newcommandDiaaParse[1]begingroupdeffrac##1##2((##1)/(##2))%
          defsqrt##1sqrt(##1)%
          defcdot*%
          deftimes*%
          defexp##1exp(##1)%
          deflog##1log(##1)%
          defln##1ln(##1)%
          defarcsin##1asin(##1)%
          defcot##1cot(##1)%
          defsin##1sin(##1)%
          defsinh##1sinh(##1)%
          defarccos##1acos(##1)%
          defcot##1cot(##1)%
          defcos##1cos(##1)%
          defarctan##1atan(##1)%
          defcot##1cot(##1)%
          deftan##1tan(##1)%
          deftanh##1tanh(##1)%
          defarccot##1acot(##1)%
          defcot##1cot(##1)%
          defcot##1cot(##1)%
          edefret#1%
          pgfmathparseret%
          pgfmathsmugglepgfmathresult%
          endgroup


          The first root is evaluated by $x_1 = toprint =DiaaParsetoprint
          SIpgfmathresultcm$

          enddocument


          enter image description here



          As you see, this does work with SI and so on, simply because it wraps the additional parsing around pgfmathparse. This also defines the replacement rules for other commands, but I stress it is fragile. Please note that this requires a rather recent version of pgf (3.1.1 or higher, I think) which has pgfmathsmuggle in it. For older versions, you have to use other smuggling techniques, see the answers of this question for possible ways.



          Overall this does something of the sort you are suggesting, but I stress it is fragile. What if a user wants to compute, say, log_7 29? Yes, one could extend the parser to deal with that as well, but this will be more effort. And then the next user wants sqrt[3]19. Also possible, but more efforts. And how about log_10 3frac14, how would the parser know that this is log(13/4)/log(7)? Of course, if you use external programs, you can avoid duplication, e.g. Mathematica has TeXForm to convert the result of some module to not-so-nice but most times working (La)TeX code.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited May 19 at 19:57

























          answered May 18 at 21:17









          marmotmarmot

          129k6163310




          129k6163310












          • Could you please suggest how to deal with the multiplication in the form of times instead of *?

            – Diaa
            May 19 at 1:04






          • 1





            @Diaa You just have to add defcdot*%, which I added in the second example.

            – marmot
            May 19 at 2:51






          • 1





            @Diaa This works the same for times: deftimes*%.

            – marmot
            May 19 at 3:25






          • 3





            @Diaa I recommend tikzmarmots. It does not produce precisely the same output, but is much more entertaining. ;-) More seriously, I can see that why folks are reluctant to write such a package. It will be (almost) inevitably fragile. So you spend 10 minutes on writing the core functions and 5 month on making it more robust. It is almost trivial to add the functions of section 94.3 Syntax for Mathematical Expressions: Functions of the pgfmanual 3.1.3 to the above parser but very hard to cope with all the ways users may typeset their expressions.

            – marmot
            May 19 at 4:14






          • 1





            @Diaa If I would have to guess, then I'd think that the author/maintainer of siunitx will have the best chances of accomplishing this. siunitx does already a lot of related things and its maintainer presumably has a very good idea of what can go wrong.

            – marmot
            May 19 at 19:55

















          • Could you please suggest how to deal with the multiplication in the form of times instead of *?

            – Diaa
            May 19 at 1:04






          • 1





            @Diaa You just have to add defcdot*%, which I added in the second example.

            – marmot
            May 19 at 2:51






          • 1





            @Diaa This works the same for times: deftimes*%.

            – marmot
            May 19 at 3:25






          • 3





            @Diaa I recommend tikzmarmots. It does not produce precisely the same output, but is much more entertaining. ;-) More seriously, I can see that why folks are reluctant to write such a package. It will be (almost) inevitably fragile. So you spend 10 minutes on writing the core functions and 5 month on making it more robust. It is almost trivial to add the functions of section 94.3 Syntax for Mathematical Expressions: Functions of the pgfmanual 3.1.3 to the above parser but very hard to cope with all the ways users may typeset their expressions.

            – marmot
            May 19 at 4:14






          • 1





            @Diaa If I would have to guess, then I'd think that the author/maintainer of siunitx will have the best chances of accomplishing this. siunitx does already a lot of related things and its maintainer presumably has a very good idea of what can go wrong.

            – marmot
            May 19 at 19:55
















          Could you please suggest how to deal with the multiplication in the form of times instead of *?

          – Diaa
          May 19 at 1:04





          Could you please suggest how to deal with the multiplication in the form of times instead of *?

          – Diaa
          May 19 at 1:04




          1




          1





          @Diaa You just have to add defcdot*%, which I added in the second example.

          – marmot
          May 19 at 2:51





          @Diaa You just have to add defcdot*%, which I added in the second example.

          – marmot
          May 19 at 2:51




          1




          1





          @Diaa This works the same for times: deftimes*%.

          – marmot
          May 19 at 3:25





          @Diaa This works the same for times: deftimes*%.

          – marmot
          May 19 at 3:25




          3




          3





          @Diaa I recommend tikzmarmots. It does not produce precisely the same output, but is much more entertaining. ;-) More seriously, I can see that why folks are reluctant to write such a package. It will be (almost) inevitably fragile. So you spend 10 minutes on writing the core functions and 5 month on making it more robust. It is almost trivial to add the functions of section 94.3 Syntax for Mathematical Expressions: Functions of the pgfmanual 3.1.3 to the above parser but very hard to cope with all the ways users may typeset their expressions.

          – marmot
          May 19 at 4:14





          @Diaa I recommend tikzmarmots. It does not produce precisely the same output, but is much more entertaining. ;-) More seriously, I can see that why folks are reluctant to write such a package. It will be (almost) inevitably fragile. So you spend 10 minutes on writing the core functions and 5 month on making it more robust. It is almost trivial to add the functions of section 94.3 Syntax for Mathematical Expressions: Functions of the pgfmanual 3.1.3 to the above parser but very hard to cope with all the ways users may typeset their expressions.

          – marmot
          May 19 at 4:14




          1




          1





          @Diaa If I would have to guess, then I'd think that the author/maintainer of siunitx will have the best chances of accomplishing this. siunitx does already a lot of related things and its maintainer presumably has a very good idea of what can go wrong.

          – marmot
          May 19 at 19:55





          @Diaa If I would have to guess, then I'd think that the author/maintainer of siunitx will have the best chances of accomplishing this. siunitx does already a lot of related things and its maintainer presumably has a very good idea of what can go wrong.

          – marmot
          May 19 at 19:55











          2














          Some years ago, I had the same problem.



          Since writing a robust parser is not a trivial exercise, I decided to not try it in TeX, but use Python (version 3.6 or later) instead.



          The result was the TeXcalc module.



          The input looks like this:



          from texcalc import Calculation

          c = Calculation()
          c.add('rho_f', '1.62', 'g/cm^3', 'Fiber density')
          c.add('rho_r', '1.2', 'g/cm^3', "Resin density")
          c.add('v_f', '0.3', '-', 'Fiber volume fraction')
          c.add('W_f', '450', 'g/m^2', "Area weight fibers", fmt=".0f")
          c.add('t_f', 'W_f/(10000*rho_f)*10', 'mm')
          c.add('t', 't_f/v_f', 'mm', "Laminate thickness")
          c.add('t_r', 't-t_f', 'mm')
          c.add('W_r', 't_f/10*(10000*rho_r)', 'g/m^2', "Area weight resin", fmt=".0f")
          print(c)


          It outputs an align* environment (from the amsmath package) and uses siunitx to typeset the units. After processing with LaTeX, the output looks like this.
          TexCalc example




          Adapted to the MWE on request



          The following are the contents of mwe.py



          from texcalc import Calculation

          c = Calculation()
          c.add('b', 4)
          c.add('a', 1)
          c.add('c', 3)
          c.add('x1', '(-b+sqrt(b**2-4*a*c))/2', 'cm', 'first root')
          c.add('x2', '(-b-sqrt(b**2-4*a*c))/2', 'cm', 'second root')
          print(c)


          Run this as python3 mwe.py > foo.tex



          This is mwe.tex:



          documentclass[preview=true]standalone
          usepackageamsmath,siunitx

          begindocument
          inputfoo.tex
          enddocument


          Run this with pdflatex mwe.tex.



          This results in:
          MWE image



          The goal of TeXcalc is to clarify complicated calculations that have multiple steps, as shown in the first example. This to make it easier for others to follow.



          So it cannot exactly match your MWE, since it doesn't produce in-line math. Although in this case, you could extract the necessary data from foo.tex.






          share|improve this answer




















          • 1





            Your answer looks interesting. Could you please adapt it to my MWE?

            – Diaa
            May 19 at 10:18






          • 1





            @Diaa: See updated answer.

            – Roland Smith
            May 19 at 17:23















          2














          Some years ago, I had the same problem.



          Since writing a robust parser is not a trivial exercise, I decided to not try it in TeX, but use Python (version 3.6 or later) instead.



          The result was the TeXcalc module.



          The input looks like this:



          from texcalc import Calculation

          c = Calculation()
          c.add('rho_f', '1.62', 'g/cm^3', 'Fiber density')
          c.add('rho_r', '1.2', 'g/cm^3', "Resin density")
          c.add('v_f', '0.3', '-', 'Fiber volume fraction')
          c.add('W_f', '450', 'g/m^2', "Area weight fibers", fmt=".0f")
          c.add('t_f', 'W_f/(10000*rho_f)*10', 'mm')
          c.add('t', 't_f/v_f', 'mm', "Laminate thickness")
          c.add('t_r', 't-t_f', 'mm')
          c.add('W_r', 't_f/10*(10000*rho_r)', 'g/m^2', "Area weight resin", fmt=".0f")
          print(c)


          It outputs an align* environment (from the amsmath package) and uses siunitx to typeset the units. After processing with LaTeX, the output looks like this.
          TexCalc example




          Adapted to the MWE on request



          The following are the contents of mwe.py



          from texcalc import Calculation

          c = Calculation()
          c.add('b', 4)
          c.add('a', 1)
          c.add('c', 3)
          c.add('x1', '(-b+sqrt(b**2-4*a*c))/2', 'cm', 'first root')
          c.add('x2', '(-b-sqrt(b**2-4*a*c))/2', 'cm', 'second root')
          print(c)


          Run this as python3 mwe.py > foo.tex



          This is mwe.tex:



          documentclass[preview=true]standalone
          usepackageamsmath,siunitx

          begindocument
          inputfoo.tex
          enddocument


          Run this with pdflatex mwe.tex.



          This results in:
          MWE image



          The goal of TeXcalc is to clarify complicated calculations that have multiple steps, as shown in the first example. This to make it easier for others to follow.



          So it cannot exactly match your MWE, since it doesn't produce in-line math. Although in this case, you could extract the necessary data from foo.tex.






          share|improve this answer




















          • 1





            Your answer looks interesting. Could you please adapt it to my MWE?

            – Diaa
            May 19 at 10:18






          • 1





            @Diaa: See updated answer.

            – Roland Smith
            May 19 at 17:23













          2












          2








          2







          Some years ago, I had the same problem.



          Since writing a robust parser is not a trivial exercise, I decided to not try it in TeX, but use Python (version 3.6 or later) instead.



          The result was the TeXcalc module.



          The input looks like this:



          from texcalc import Calculation

          c = Calculation()
          c.add('rho_f', '1.62', 'g/cm^3', 'Fiber density')
          c.add('rho_r', '1.2', 'g/cm^3', "Resin density")
          c.add('v_f', '0.3', '-', 'Fiber volume fraction')
          c.add('W_f', '450', 'g/m^2', "Area weight fibers", fmt=".0f")
          c.add('t_f', 'W_f/(10000*rho_f)*10', 'mm')
          c.add('t', 't_f/v_f', 'mm', "Laminate thickness")
          c.add('t_r', 't-t_f', 'mm')
          c.add('W_r', 't_f/10*(10000*rho_r)', 'g/m^2', "Area weight resin", fmt=".0f")
          print(c)


          It outputs an align* environment (from the amsmath package) and uses siunitx to typeset the units. After processing with LaTeX, the output looks like this.
          TexCalc example




          Adapted to the MWE on request



          The following are the contents of mwe.py



          from texcalc import Calculation

          c = Calculation()
          c.add('b', 4)
          c.add('a', 1)
          c.add('c', 3)
          c.add('x1', '(-b+sqrt(b**2-4*a*c))/2', 'cm', 'first root')
          c.add('x2', '(-b-sqrt(b**2-4*a*c))/2', 'cm', 'second root')
          print(c)


          Run this as python3 mwe.py > foo.tex



          This is mwe.tex:



          documentclass[preview=true]standalone
          usepackageamsmath,siunitx

          begindocument
          inputfoo.tex
          enddocument


          Run this with pdflatex mwe.tex.



          This results in:
          MWE image



          The goal of TeXcalc is to clarify complicated calculations that have multiple steps, as shown in the first example. This to make it easier for others to follow.



          So it cannot exactly match your MWE, since it doesn't produce in-line math. Although in this case, you could extract the necessary data from foo.tex.






          share|improve this answer















          Some years ago, I had the same problem.



          Since writing a robust parser is not a trivial exercise, I decided to not try it in TeX, but use Python (version 3.6 or later) instead.



          The result was the TeXcalc module.



          The input looks like this:



          from texcalc import Calculation

          c = Calculation()
          c.add('rho_f', '1.62', 'g/cm^3', 'Fiber density')
          c.add('rho_r', '1.2', 'g/cm^3', "Resin density")
          c.add('v_f', '0.3', '-', 'Fiber volume fraction')
          c.add('W_f', '450', 'g/m^2', "Area weight fibers", fmt=".0f")
          c.add('t_f', 'W_f/(10000*rho_f)*10', 'mm')
          c.add('t', 't_f/v_f', 'mm', "Laminate thickness")
          c.add('t_r', 't-t_f', 'mm')
          c.add('W_r', 't_f/10*(10000*rho_r)', 'g/m^2', "Area weight resin", fmt=".0f")
          print(c)


          It outputs an align* environment (from the amsmath package) and uses siunitx to typeset the units. After processing with LaTeX, the output looks like this.
          TexCalc example




          Adapted to the MWE on request



          The following are the contents of mwe.py



          from texcalc import Calculation

          c = Calculation()
          c.add('b', 4)
          c.add('a', 1)
          c.add('c', 3)
          c.add('x1', '(-b+sqrt(b**2-4*a*c))/2', 'cm', 'first root')
          c.add('x2', '(-b-sqrt(b**2-4*a*c))/2', 'cm', 'second root')
          print(c)


          Run this as python3 mwe.py > foo.tex



          This is mwe.tex:



          documentclass[preview=true]standalone
          usepackageamsmath,siunitx

          begindocument
          inputfoo.tex
          enddocument


          Run this with pdflatex mwe.tex.



          This results in:
          MWE image



          The goal of TeXcalc is to clarify complicated calculations that have multiple steps, as shown in the first example. This to make it easier for others to follow.



          So it cannot exactly match your MWE, since it doesn't produce in-line math. Although in this case, you could extract the necessary data from foo.tex.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited May 19 at 19:21

























          answered May 19 at 6:32









          Roland SmithRoland Smith

          38115




          38115







          • 1





            Your answer looks interesting. Could you please adapt it to my MWE?

            – Diaa
            May 19 at 10:18






          • 1





            @Diaa: See updated answer.

            – Roland Smith
            May 19 at 17:23












          • 1





            Your answer looks interesting. Could you please adapt it to my MWE?

            – Diaa
            May 19 at 10:18






          • 1





            @Diaa: See updated answer.

            – Roland Smith
            May 19 at 17:23







          1




          1





          Your answer looks interesting. Could you please adapt it to my MWE?

          – Diaa
          May 19 at 10:18





          Your answer looks interesting. Could you please adapt it to my MWE?

          – Diaa
          May 19 at 10:18




          1




          1





          @Diaa: See updated answer.

          – Roland Smith
          May 19 at 17:23





          @Diaa: See updated answer.

          – Roland Smith
          May 19 at 17:23

















          draft saved

          draft discarded
















































          Thanks for contributing an answer to TeX - LaTeX Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2ftex.stackexchange.com%2fquestions%2f491540%2fbest-practice-for-printing-and-evaluating-formulas-with-the-minimal-coding%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Get product attribute by attribute group code in magento 2get product attribute by product attribute group in magento 2Magento 2 Log Bundle Product Data in List Page?How to get all product attribute of a attribute group of Default attribute set?Magento 2.1 Create a filter in the product grid by new attributeMagento 2 : Get Product Attribute values By GroupMagento 2 How to get all existing values for one attributeMagento 2 get custom attribute of a single product inside a pluginMagento 2.3 How to get all the Multi Source Inventory (MSI) locations collection in custom module?Magento2: how to develop rest API to get new productsGet product attribute by attribute group code ( [attribute_group_code] ) in magento 2

          Category:9 (number) SubcategoriesMedia in category "9 (number)"Navigation menuUpload mediaGND ID: 4485639-8Library of Congress authority ID: sh85091979ReasonatorScholiaStatistics

          Magento 2.3: How do i solve this, Not registered handle, on custom form?How can i rewrite TierPrice Block in Magento2magento 2 captcha not rendering if I override layout xmlmain.CRITICAL: Plugin class doesn't existMagento 2 : Problem while adding custom button order view page?Magento 2.2.5: Overriding Admin Controller sales/orderMagento 2.2.5: Add, Update and Delete existing products Custom OptionsMagento 2.3 : File Upload issue in UI Component FormMagento2 Not registered handleHow to configured Form Builder Js in my custom magento 2.3.0 module?Magento 2.3. How to create image upload field in an admin form