MathGroup Archive 2008

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: How to hold a form and convert it to a string

  • To: mathgroup at smc.vnet.net
  • Subject: [mg93929] Re: How to hold a form and convert it to a string
  • From: Jens-Peer Kuska <kuska at informatik.uni-leipzig.de>
  • Date: Fri, 28 Nov 2008 07:11:40 -0500 (EST)
  • Organization: Uni Leipzig
  • References: <ggog1m$s6g$1@smc.vnet.net>
  • Reply-to: kuska at informatik.uni-leipzig.de

Hi,

the answer is just across the corridor

HornerForm[a*q + b*q^2 + c*q^3, q] // CForm // ToString

does not use Power[] at all and is more efficient in the numerical
evaluation than a*q + b*q*q + c*q*q*q

In Mathematica alone

Unprotect[Power]
Power /: MakeBoxes[a_^n_Integer, fmt_: StandardForm] := RowBox[
   Riffle[Table[ToString[a], {n}], "*"]]
Protect[Power]

will solve the problem

And for CForm the definition:

ClearAttributes[Power, Protected]

Format[Power[a_Symbol, n_Integer], CForm] :=
  ToExpression[StringJoin @@ Riffle[Table[ToString[a], {n}], "*"],
   InputForm, HoldForm]

Protect[Power]

will produce

a*q + b*q^2 + c*q^3 // CForm

a*q + b*(q*q) + c*(q*q*q)

Regards
   Jens

re
Patrick Scheibe wrote:
> Hi,
> 
> I'm sure it's a simple question but I don't get it. I want to transform
> the expression
> 
> a*q + b*q^2 + c*q^3
> 
> into a C-Code form
> 
> "a*q + b*q*q + c*q*q*q"
> 
> With the rule
> exp //. (Power[q_, n_] :> Times@@Array[q &, n])
> for the transformation of the Power of q,
> the expression is instantly reevaluated to the first form (as I expected
> it). I could transform the complete first expression to a C-Form-String
> and manipulate this. This would look like
> 
> f[exp_] := StringReplace[ToString@CForm[exp],
>   "Power(" ~~ q_ ~~ "," ~~ n_ ~~ ")" :>
>    StringJoin[Riffle[Array[ToString@q &, ToExpression[n]], "*"]]]
> 
> Isn't there a more stylish way?
> 
> Cheers
> Patrick
> 


  • Prev by Date: Re: Package Problem
  • Next by Date: Re: Package Problem
  • Previous by thread: How to hold a form and convert it to a string
  • Next by thread: Re: How to hold a form and convert it to a string