Message Boards Message Boards

0
|
3188 Views
|
4 Replies
|
0 Total Likes
View groups...
Share
Share this post:

Speed up a function with Element[], ToString[]?

Posted 8 years ago
xNull = {0, 0, 0};
            sin[{i_, k_, j_}] :=
              If[k > 0 && Element[i, Reals] === True, h = N[Sin[i]]; If[Element[h, Reals] === True, {h, k, ToString["Sin(" <> j <> ")"]}, xNull], xNull];

            For[i = 1., i <= 1000000., i++, x = sin[{7.5, 3.2, "xNm"}]] // AbsoluteTiming
            x
        {7.32883, Null}
        {0.938, 3.2, "Sin(xNm)"}

How can I optimize this function, I need only draw any real number and if they are not, I must return {0,0,0}

i_ must be a real number with a precision of 16, k_ cheh a decimal number ranging from 0.0 to 9.9 with a careful precision of one decimal number, j_ is a text string

POSTED BY: Paolo Pellegrini
4 Replies

This is a bit faster, but it may or may not give the exact number format that you want:

SumLev2[k_] := 
  IntegerPart[(Max[Floor[k]] + Total[FractionalPart[k]])*10]/10.;

If you work with floating-point inputs only, compilation may help with speed, but I don't have expertise in that area.

POSTED BY: Gianluca Gorni

OK thanks. you may also optimize this? thanks :-)

SumLev[k_] := N[IntegerPart[(Max[Floor[k]] + Total[ FractionalPart[k]])*10]/10, 2];

example: k = {3.2, 4.2, 1.9} = Max(3,4,1) + (0.2+0.2+0.9) = 4 + 1.3 = 5.3
POSTED BY: Paolo Pellegrini

A little bit faster without the redundant N:

Clear[sin];
sin[{i_Real, k_?Positive, j_String}] := {Sin[i], k, "Sin(" <> j <> ")"};
sin[_] = {0, 0, 0};
POSTED BY: Gianluca Gorni

This may be a little faster:

Clear[sin];
sin[{i_Real, k_?Positive, j_String}] := {N[Sin[i]], k, 
   "Sin(" <> j <> ")"};
sin[_] = {0, 0, 0};
POSTED BY: Gianluca Gorni
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract