Message Boards Message Boards

3 Replies
2 Total Likes
View groups...
Share this post:

What's wrong with this code?

Posted 11 years ago
Clear[r, len, lenn, alpha, prec];
r = 0;
prec = 50;
len = 2;
lenn = len - 1;
If[r < len - 1,      <-----problem here, I can change "len-1" to "lenn" and it still has a problem, if I change it to "len" it works 
alpha = N[r, prec]   <---simplified here, but I want to run multiple lines of code if this condition is true, maybe there's a "better" way to do this? 

Hi all, I'm new to mathematica and have to program an algorithm for a maths class.  We have minimal training in mathematica, focusing more on the maths, but this is a simplification of some code that is giving me problems I just cannot comprehend.

Basically, the variable "alpha" keeps showing up in blue as not recognised, unless I set the "len-1" to len.  Why is it doing that?
POSTED BY: Steven Thomas
3 Replies
Your "then" condition isn't running, so what happens is that you are Clearing alpha at the top and it's never set to anything, so it stays unassigned. The code works for me, so I'm not sure what might be the exact issue. Maybe you have an extra comma somewhere. If you have an extra comma after the If condition, your alpha assignment will be in the "else" slot (with a Null "then" slot).

Something else you can do is just see what (r < len - 1) returns by itself. `If` has a symbolic interpretation when it can't reduce the condition to True or False, in which case the whole If expression is returned as a result and nothing will be executed (in part this is for the sake of things like piecewise functions). You can check the documentation for the If function to see its forms. And in general, make sure you are always making use of the F1 key. It's the bestest feature of Mathematica.
Posted 11 years ago
Maybe it DOES work, it's just the editor that has the problem.  It throws me everytime it highlights something in blue, makes me think my code has a problem (which it usually does).

It's just I cannot fathom why if instead of


I type:


It still highlights "alpha" in blue, but if I use:


It has no problem at all.  I just see no logic to it at all.  Gotta try on another computer.

Oh yeah, F1 is great when I'm on a Windows machine, then I switched to a MAC and F1 dims the screen, haven't figured that one out yet!
POSTED BY: Steven Thomas
Thomas, please take a few minutes to read this tutorial about correct posting – especially of Mathematica code:

How to type up a post: editor tutorial & general tips

If you will not follow the tutorial, other members of community may not be able to test your code. To edit your post – click “Edit” in the lower right corner of your post.
POSTED BY: Moderation Team
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
or Discard

Group Abstract Group Abstract