Message Boards Message Boards

11
|
36574 Views
|
186 Replies
|
92 Total Likes
View groups...
Share
Share this post:

[WSG22] Daily Study Group: A Guide to Programming and Mathematics with WL

A new study group on the topic "A Guide to Programming and Mathematics with the Wolfram Language" will begin soon.

Join a cohort of fellow learners and expand your understanding of core programming topics as well as symbolic and applied mathematics functionality in the Wolfram Language with lessons by veteran instructor and developer David Withoff. A basic working knowledge of the Wolfram Language or introductory-level skill in any programming language is recommended.

April 18–May 6

11am–12pm US CT (4–5pm GMT)

REGISTER HERE

enter image description here

186 Replies

After one passes the three quizzes, what does one do to receive certification?

POSTED BY: Thomas Rike

We will reach out to you with your certificate.

Thanks for the reply.

POSTED BY: Thomas Rike

Hi Conrad,

If "4" is assigned to p, and then you look at the head of p: Head[p], it will still be a string. The quotes just aren't shown but it p still acts like a string.

p = "\"4\""

This will show the quotes and p will still behave like a string.

Is that what you needed?

Lori

POSTED BY: Lori Johnson

Hi Lori, thanks for getting back to me. Anyway, I guess I was really looking for a setting within Mathematica to always show the quotes for an output string.

POSTED BY: Conrad Taylor

Conrad, I suppose you could dig into Global Preferences, but I personally wouldn't bother if your code is behaving as expected.

What exactly are you trying to do?

POSTED BY: Lori Johnson

@Lori Johnson It's just a personal preference to see strings with double quotes in the output.

POSTED BY: Conrad Taylor

Understood! :D

POSTED BY: Lori Johnson
Posted 2 years ago

Hi Conrad,

You can use the cell option ShowStringCharacters. See this answer on MSE.

POSTED BY: Rohit Namjoshi

@Rohit Namjoshi Thanks for the references and I'll definitely take a look at the links.

POSTED BY: Conrad Taylor

How does one always show the double quotes around a string? For example, I'm currently seeing this behavior:

enter image description here

POSTED BY: Conrad Taylor
Posted 2 years ago

POSTED BY: Syd Geraghty
Posted 2 years ago

Clearly Element[, Reals] and _Real treat the symbols differently.

Element[#,Reals]&/@{3.1,Pi,\[Pi],E}
{True,True,True,True}
Developer`RealQ/@{3.1,Pi,\[Pi],E}
{True,False,False,False}

My guess is: _Real probably only mean real number. Element will check if the symbol really represent a real number. If you want the behavior of Element, you can use this:

Replace[{3.1,Pi,\[Pi],E},{p_/;Element[p,Reals]->Framed[p]},1]
POSTED BY: Jin Zhang
Posted 2 years ago
Replace[{3.1,Pi,\[Pi],E,10,21},{x_/;Element[x,Reals]->Framed[x]},{1}]

Unfortunately this also selects the Integers 10 and 21 which is the wrong requirement!

POSTED BY: Syd Geraghty
Posted 2 years ago

Reals is a domain specification. The domain of reals includes the integers. See Wikipedia.

POSTED BY: Rohit Namjoshi
Posted 2 years ago

Pi is not a Real, but a Symbol

Replace[{3.1, \[Pi], Pi, \[Pi], 10, 3.14159, E}, { 
  x_ /; (MemberQ[{Real, Symbol}, Head[x]]) -> Framed[x]}, {1}]

creates frames for all but the Integer enter image description here

POSTED BY: Peter Lippolt
Posted 2 years ago

Hi, I am a bit confused about quiz 3.4. My code gives exactly the same expected output. But 'Check my solution' gives a red cross. I am wondering if I need to take care of the case '0'->'-1' to be '0'->'9'. Even I did that, I still cannot pass the check. Any idea?

POSTED BY: Jin Zhang

I'm really not understanding what upvalues, downvalues, ownvalues, etc. are. Not how they're used, but what they are. I can find the documentation about them in the documentation center, but I never saw that it defines what they are. Can anyone help?

POSTED BY: Kari Grafton

Yes, the documentation didn't clearly explain DownValues, UpValues, or OwnValues. However, here's a very good write up for reference:

https://mathematica.stackexchange.com/questions/96/what-is-the-distinction-between-downvalues-upvalues-subvalues-and-ownvalues

I wish that this helps you to better understand their definitions.

POSTED BY: Conrad Taylor
Posted 2 years ago

Quiz 3.3 question:

I am stuck on only one output detail with this question and it appeared as a very straightforward piece of code that just doesn't work! Where am I going wrong, what am I missing?

In[84]:= 
Element[\[Pi], #] & /@ {Complexes, Algebraics, Reals, Rationals, 
  Integers, Primes}

Out[84]= {True, False, True, False, False, False}

So Pi belongs to the domain of Reals!

However any of the input variants for Pi cannot be framed as expected with this Replace code:

Try inputting Pi in different ways ...\ [Pi], [FpormaPi], esc pi esc, ...

In[82]:= Replace[{3.1, \[Pi], Pi, \[Pi], 3.14159, E}, {x_Real -> Framed[x]}, {1}]

Out[82]= {
\!\(\*FrameBox[\!\(3.1`\),
StripOnInput->False]\), \[Pi], \[Pi], \[Pi], 
\!\(\*FrameBox[\!\(3.14159`\),
StripOnInput->False]\), E}

How do I frame the Pi symbol?

Syd

POSTED BY: Updating Name

Hi,

I was wondering if the 3rd quiz automatically is submitted after checking all the solutions. I don't see any sort of submit button so I hope I managed to make everything work. Let me know if I'm missing something.

Thanks!

@Aristarque Monneron yes, each solution to the programming exercises in quiz 3 gets automatically graded and submitted when you click "Check Solution". We see your submissions for quiz 1 and 2 but not for quiz 3. Could you please email wolfram-u@wolfram.com and follow up with your notebook?

Hi Abrita,

I have sent an email with the file to the address indicated.

Posted 2 years ago

Confirmation of quiz completion?

Hi Abrita: Many thanks to you and to the team for the presentations. I have submitted the quizzes (1,2,3(part)) and seen the confirmed "OK"s for correct answers: but no overall "congratulations, we'll get back to you" message. Is such a thing expected, to reassure me before the deadline? Thanks Peter (peter.ransome@ieee.org)

POSTED BY: Peter Ransome

@Peter Ransome Yes all your submissions have been received.

Posted 2 years ago

Hi Mitchell

I think Abrita's comment is quite clear on where ToString is not needed

Firstly {"a3bykmn","oka2bcka","bdkba1","4ckxyz"} is already a list of Strings so you do not need ToString for the input.

and where it is needed

You would need to use ToString to convert the digit back to String once you have isolated it and decremented it by 1

The code you posted earlier is close

StringReplace[{"a3bykmn","oka2bcka","bdkba1","4ckxyz"},p:DigitCharacter :>ToExpression[p-1]]

Just need to fix the ToExpression[p-1]]. p is a String, it needs to be converted to an Integer so 1 can be subtracted from it, the result needs to be converted to a String so StringReplace can do the replacement.

POSTED BY: Rohit Namjoshi

Got It. Thanks so much.

Mitch Sandlin

POSTED BY: Mitchell Sandlin

Hi;

Based on the definition and hints given by the problem, I think that everything is included in my solution, however I am not getting the desired output - see below. I am sure that it is something that I am doing incorrectly, but based on my knowledge at this point in time, I do not have a clue.

StringReplace[ToString[{"a3bykmn","oka2bcka","bdkba1","4ckxyz"}],p_DigitCharacter :>ToExpression[p-1]]
POSTED BY: Mitchell Sandlin

Firstly {"a3bykmn","oka2bcka","bdkba1","4ckxyz"} is already a list of Strings so you do not need ToString for the input. You would need to use ToString to convert the digit back to String once you have isolated it and decremented it by 1.

As the error message says, "StringExpression::invld: Element pDigitCharacter is not a valid string or pattern element in pDigitCharacter:>ToExpression[p-1]."

Remember if you are trying to restrict a pattern to match only expressions with a certain Head that is when you use the Underscore "_". So you can have "p_Integer" or "p_String" etc. When you want to use a pattern object like "DigitCharacter" or "PunctuationCharacter" we want to simply follow up the name with ":" like p:DigitCharacter or p:PunctuationCharacter

StringCases["\"a, b c.\"", p : PunctuationCharacter :> Framed[Style[p, Red]]]

Hi Abrita;

I incorporated the changes that you suggested (see below) and this time, I think the program actually blew up because I never received an answer back as to whether the program actually completed. In any event, I am not getting an option to try again.

However, the comments as to when to use an _ verses a : were very helpful.

StringReplace[{"a3bykmn","oka2bcka","bdkba1","4ckxyz"},p:DigitCharacter :>ToExpression[p-1]]
POSTED BY: Mitchell Sandlin
Posted 2 years ago

The error message is

ToExpression::notstrbox: -1+3 is not a string or a box. ToExpression can only interpret strings or boxes as Wolfram Language input.

p is a String, so ToExpression[p-1] fails. Cannot subtract 1 from a String.

Hint: ToExpression["3"] // Head

POSTED BY: Rohit Namjoshi

Hi Rohit;

The problem stated as hints that ToString[] and ToExpression[] would be needed in the solution of StringReplace[]. Abrita told me in a previous reply that I really didn't need to use ToString since the data was already in string format, so I remove it from my expression.

I need to read the digit characters from the data strings, for example pull the 3 from the first string a3bykmn, then subtract 1 from the value, write it back out as a 2, and then grab the next digit character from the next string oka2bcka which is a 2 subtract 1 giving 1 and so on.

Even after attending every lecture, I don't know how to do that.

Thanks,

Mitch Sandlin

POSTED BY: Mitchell Sandlin

Hi Mitch, Sorry for the confusion. I meant "you do not need ToString for the input", but you will need it when your pattern has found a match. In your code:

StringReplace[{"a3bykmn","oka2bcka","bdkba1","4ckxyz"},p:DigitCharacter :>ToExpression[p-1]]

once p has matched something it is still a string, that is why you cannot subtract 1 from it. You need to convert it into an expression to subtract 1 from it. Once that is done, you want to put it back in the original string, but now again you are stuck with an integer you are trying to insert into a string. This is where ToString comes in handy.

ToExpression can convert string to number i.e. "3" to 3 ToString can convert a number to a string i.e. 3 to "3"

Hope this helps.

Hi Abrita; Referring to 3.3 we are instructed to use Replace[] along with a set of rules to process even, odd and non integers. My solution only wants to process the first element of the string - see below.

Clear[x,y,z]
Replace[#,{x_/;EvenQ[x]->x*2,y_/;OddQ[y]->y*3,z_/;!IntegerQ[z]->Framed[z]}]&  [94,87,[Pi],49,46,"42",28,47,68,57,4,44,100,4.2,{23,1},57]

For example, if you run the function, it will return 188 (294). If you replace the first element of 94 with 87 and run the function, it will return 261 (387). If you replace the first element of 94 with Pi and run the function, it will return Pi with a box around it. Therefore, the logic seems to be working correctly, I just can't get the evaluation to move through the list, and I think I have tried everything that I can find in the documentation as well as the lecture notes. Do you have any suggestions.

Thanks, Mitch Sandlin

POSTED BY: Mitchell Sandlin

On Quiz 3 Problem 3.1, when I click Check My Solution, I getenter image description here the following error within the downloaded notebook:

POSTED BY: Conrad Taylor

@Conrad Taylor Referring to the third template for creating a SparseArray on http://reference.wolfram.com/language/ref/SparseArray.html SparseArray[data,{d1,d2, ...}], we would like you to create your own 'data' with a rule (of the form pattern -> value). The example showing the construction of a tridiagonal matrix using patterns for indices on the documentation page linked above, may be a good starting point to solve this problem.

Hi Abrita;

I followed the example in the link that you sent me for SparceArray to create the data and again it produced exactly the same correct output in the MatrixPlot that the problem indicated it should. However, I am again getting the message that my answer is incorrect and to try again.

Mitch Sandlin

POSTED BY: Mitchell Sandlin

Hi Conrad;

I followed the example that you sent me a link to for SparceArray and again produced exactly the same output as the problem displayed, but still was not accepted as the correct answer. I do not know that to do at this point. Any suggestions.

Mitch Sandlin

POSTED BY: Mitchell Sandlin
Posted 2 years ago

Hi Mitch

Regarding Q1 , there is a grader issue .

I will just recount my approach to doing qustion1 :- I answer the question without looking at the hints . My first approach was to create the data within the SparesArray[] function and got the correct output but the grader did not accept it. After a number of ways of creating the data within the SparesArray[] function and no success., I then looked at the hints

    DATA=................
    SparseArray[DATA ,{n,n}]

So the DATA had to be created outside the SparseArray in a full array :-

    DATA="full array" /"standard matrix " 
    SparseArray[DATA ,{n,n}]

with the correct values for n ,the grader accepted ,

POSTED BY: Doug Beveridge

Hi Doug;

Following your advice, I deleted my data from my SparseArray[] and moved it into a field named dta1= {{1,5}-> 1, etc.}}. Then loaded the data into the functions:

MatrixPlot[SparseArray[dta1,{20,20}]]

The new configuration gave me the exact same data as expected, as I have gotten for the last 5 days, with no error messages. However again, the grader didn't like it, gave me an X and told me to try again.

Thanks,

Mitch Sandlin

POSTED BY: Mitchell Sandlin
Posted 2 years ago

Mitch

As a side note , make sure there are no blank spaces in your code eg

Function[x_   ,  y_ ] 

should be

   Function[x_,y_]

This used to cause major problems with the g4rader

POSTED BY: Doug Beveridge

Hi, I was able to refactor Quiz 3 Problem 3.1 into a solution that appears to have been accepted by the backend. Also, I was definitely in the weeds for this problem. Anyway, could someone confirm that I have submitted all 3 quizzes for the study group?

POSTED BY: Conrad Taylor

Hello;;

I cannot figure out why my If statements are not working, Please see below. I believe my If statements are pretty straight forward.

I am first checking if my retrieved value is an integer and if false, I put a box around it. If true, I run another If statement to see if it is even, if true, I simply multiply it by 2, if false, I multiply it by 3.

Additionally, I am not even sure it function is reading the data, but I thought I would work on getting the If statements working first.

ReplaceAll[x,x:>{If[IntegerQ[x],If[EvenQ[x],x*2,x*3],Framed[x]]}]{94,87,\[Pi]}

{FrameBox["x", StripOnInput -> False]} {94,87,[Pi]}

Thanks,

Mitch Sandlin

POSTED BY: Mitchell Sandlin
Posted 2 years ago

ReplaceAll[x will only match a literal x e.g.

ReplaceAll[x :> y][{a, x, x^2}]
(* {a, y, y^2} *)

For this quiz question use Replace with a level specification (which is what the quiz asks for). Rather than nested If, consider using Which.

POSTED BY: Rohit Namjoshi

Hi;

Based on the definition and hints given by the problem, I think that everything is included in my solution, however I am not getting the desired output - see below. I am sure that it is something that I am doing incorrectly, but based on my knowledge at this point in time, I do not have a clue.

StringReplace[ToString[{"a3bykmn","oka2bcka","bdkba1","4ckxyz"}],p_DigitCharacter :>ToExpression[p-1]]
POSTED BY: Mitchell Sandlin

Hi Rohit;

Thanks for the reply directing me to use Which[] as opposed to using a nested If[]. However, I still do not understand why the nested If[] failed. I actually believe the Which[] is a much cleaner solution but unfortunately it doesn't seem to work either - see below. I actually tried both formats using RelpaceAll[] and // with no success.

As an aside, I even tried using x--EvenQ[x], x*2, with no success.

ReplaceAll[x,x:>Which[EvenQ[x],x*2,OddQ[x],x*3,!IntegerQ[x],Framed[x]]]{94,87,\[Pi]}

{94,87,\[Pi]}//.x_:>Which[EvenQ[x],x*2,OddQ[x],x*3,!IntegerQ[x],Framed[x]]
POSTED BY: Mitchell Sandlin

Hi Rohit;

After completing on question in 5 days, I am focusing my attention on another problem that I am having problems with dealing with the Replace and nested If[] statements.

Following your advice, I replaced the nested If[] with the When[] function. However, the When[] function seems to have exactly the same issue as the nested If[] by not being able to recognize whether x is either: EvenQ[] an OddQ[] or !IntegerQ[] - see below.

Clear[x]    
Replace[#,x_ -> Which[EvenQ[x],x*2,OddQ[x],x*3,!IntegerQ[x],Framed[x]]]&  [94,87,[Pi],49,46,"42",28,47,68,57,4,44,100,4.2,{23,1},57]

Which gives the results of 94 with a box around it. If I enclose the data in {} as you would normally do with a list, then all the data is outputted with a box around it.

Over the last 5 days, I have tried a bunch of things to get the conditional statements to process my defined x value, with absolutely no success. According to my understanding of the documentation my conditional statements should work, and they should have worked with the nested If[] statement.

When something doesn't work, it is generally my fault, but I am lost on this problem. Any suggestions?

Thanks,

Mitch Sandlin

POSTED BY: Mitchell Sandlin
Posted 2 years ago

You are welcome, Abrita. I will post it as a separate post as well.

POSTED BY: Dave Middleton
Posted 2 years ago

POSTED BY: Dave Middleton

@Dave Middleton this is fantastic, especially in helping new users to find their way around the Entity framework. Can I request you to submit your notebook to the Notebook Archive and also create an independent post on community? You can add the groups like "Wolfram Language" or "Education" as well as "Data Science" when you post.

Hi Dave,

This is so good that I had to save a copy. Thanks for your hard work!

L

POSTED BY: Lori Johnson
Posted 2 years ago

You're welcome Lori.

Even though the exercise to create a short tutorial made me wiser, I will still refer to it whenever I need entities :)

POSTED BY: Dave Middleton

It seems absolutely necessary because of the myriad of ways to do things in WL and have files with favorite snippets based on certain functions that I use for the same purpose in clearer language! You know, like IBM mainframe manuals!

POSTED BY: Lori Johnson

I'm working on Quiz 3 Problem 3.3. I have created a function, transform, that fulfills cases 1 - 3 and returns the correct value depending on the input. Now, I'm trying to integrate the function, transform, as a rule to the Replace function. Is there something that I'm missing within the current implementation?

enter image description here

POSTED BY: Conrad Taylor
Posted 2 years ago

Hi Conrad,

/; (Condition) requires a predicate function to perform the test. From the documentation

{6, -7, 3, 2, -1, -2} /. x_ /; x < 0 -> w

Try something like

Replace[numbers, value_ :> transform[value]]

and don't forget the hint in the question.

POSTED BY: Rohit Namjoshi

@Rohit Namjoshi I was able to refactor into a better solution. Thanks for your assistance.

POSTED BY: Conrad Taylor
Posted 2 years ago

Hi, I'm only seeing 5 questions in Quiz 3. Is this correct? Ron Goetz

POSTED BY: Updating Name

Yes Quiz 3 has only 5 questions.

Posted 2 years ago

Is there a way to get a list of all Developer' functions ?

eg Developer`RealQ

and

Developer`MachineRealQ

POSTED BY: Doug Beveridge
Posted 2 years ago

Hi Doug,

Names ["Developer`*"] // 
  Partition[#, UpTo@3] & // 
  Grid[#, Alignment -> Left, Frame -> All] &
POSTED BY: Rohit Namjoshi

Hi, I just completed Quiz 1 and clicked the click Get Results. However, it's not clear how to determine that the quiz was submitted successfully. Can someone confirm that Quiz 1 has been submitted?

POSTED BY: Conrad Taylor
Posted 2 years ago

Conrad

If you press Get Results After a few seconds you should see your score below the button

enter image description here

Sometimes no score is given (I think the server may be too busy , or my connection is too slow ) and I just repeat the procedure until I get a score

POSTED BY: Doug Beveridge

@Conrad Taylor received your submissions

Hi;

Working on problem 3.4, I have tried a number of techniques with absolutely no success. I can't seem to get the number recognized as a number since the If statement doesn't want to subtract 1 and I seem to be fighting constant errors. In the code below, I am outputting the whole If statement which highlights the problem. Any suggestions as to what I may be doing incorrectly?

StringReplace[ToString[a3bykmn],p_ :> If[DigitCharacter[p],p-1,p]]


If[DigitCharacter[a],a-1,a]~~If[DigitCharacter[3],3-1,3]~~If[DigitCharacter[b],b-1,b]~~If[DigitCharacter[y],y-1,y]~~If[DigitCharacter[k],k-1,k]~~If[DigitCharacter[m],m-1,m]~~If[DigitCharacter[n],n-1,n] 

When I move the RuleDelayed to the end of the statement, all I get is an error.

StringReplace[ToString[a3bykmn],{p_ , If[DigitCharacter[p],p-1,p]} :>P]
POSTED BY: Mitchell Sandlin
Posted 2 years ago

Hi Mitchell,

DigitCharacter does not take any arguments, it matches a digit character in a StringExpression. It is not a predicate function. From the documentation

StringMatchQ[#, DigitCharacter] & /@ {"1", "a", "2", "b", ".", " "}

So the pattern given to StringReplace must contain DigitCharacter to match the digits in the input string. It can be bound to a symbol e.g. d : DigitCharacter, then d can be used in the replacement Rule.

POSTED BY: Rohit Namjoshi

Hi;

What am I doing wrong here on the 1st problem - see below? I have included everything the problem indicates, but I am getting a syntax error regarding the position of my rule.

MatrixPlot[ SparseArray[data,{n,n} /;n>0]]

Thanks,

Mitch Sandlin

POSTED BY: Mitchell Sandlin
Posted 2 years ago

Hi Mitch,

The wording of the question is a bit odd IMO. Look at the expected output and generate data using Rule and Condition so that you can reproduce the plot

data = (* some expression using Rule and Condition *)
MatrixPlot[SparseArray[data, {n, n}] (* This reproduces the expected output *)
POSTED BY: Rohit Namjoshi

Sorry if the question is not clear. Referring to the third template for creating a SparseArray on http://reference.wolfram.com/language/ref/SparseArray.html SparseArray[data,{d1,d2, ...}], we woul dlike you to create your own 'data' with a rule (of the form pattern -> value). The example showing the construction of a tridiagonal matrix using patterns for indices on the documentation page linked above, may be a good starting point to solve this problem.

Hi Abrita;

Please ignore my previous request for assistance on 3.3, I figured it out myself and can produce exactly the same required output, however the grader still marked them incorrect. The same can be said for 3.1, producing the correct output but the grader still marked it incorrect. So these 2 quiz questions will need to be hand graded. Questions 3.2 and 3.4 did not produce any problems since the grader correctly graded them as correct. Question 3.5, I could not produce the required output, so most likely it is incorrect - wasn't sure what was being asking to solve.

Quiz 1 and 2, I submitted sometime ago with passing grades on both.

Please let me know if you need anything else from me concerning these quizzes.

Thanks,

Mitch Sandlin

POSTED BY: Mitchell Sandlin

Thanks @Mitchell Sandlin. Please make sure you have emailed the notebook to wolfram-u@wolfram.com for manual grading.

For problem 3.5 we are asking you to explore how you can go about setting up the function definition so that answers to smaller problems (like f2], f[3], etc.) get stored for future use when the answer to a bigger problem (say f[10]) is requested. This can be done by the process of [memoization. You can incorporate memoization in this problem by getting the Wolfram Language to create downvalues automatically when it is trying to compute f[5]. In addition to the downvalues like

factorial[n_Integer/;n>=1]

and

factorial[0]

five other downvalues should be created automatically when f[5] is evaluated.

Hope this helps.

If by any chance any of your quiz notebooks on the cloud get corrupted you can follow these instructions to delete the notebooks from your cloud account and start afresh: https://www.wolframcloud.com/obj/online-courses/Published/UpdatingWolframUCourseQuizzesAndExercises.nb

Just a reminder that we start early tomorrow at 1:30 AM CT for a series review. If you were unable to put in your request for a review topic, feel free to reply to this post and add it here.

Abrita

I noticed that the 3rd Quiz doesn't have a scoring button, nor does it seem to be connected to the cloud. Are we expected to email the Quiz in? This may have been discussed in the final session which I missed but I still plan on listening to...

Thanks for the great Study Group sessions and for all the work you do!

Joe

POSTED BY: Joseph Sauvageau

You are very welcome.

When you click the "Check My Solution" button for each problem in Quiz 3, your graded submission (Correct or Incorrect) automatically gets recorded at our end. We are able to pull your total score for the quiz from those submissions.

If one downloads a copy of Quiz 3 notebook and clicks the Check My Solution, will the score get recorded in the backend? Thanks in advance for your feedback.

POSTED BY: Conrad Taylor

Yes it should.

Posted 2 years ago

Hi Abrita,

Concerning quiz 3, I'm experiencing similar issues I encountered in previous DSGs in that I get some answers marked as wrong (3.4 and 3.5 in this case) despite I can reproduce the expected output by using the required functions as stated in the questions. Should I send a local copy of the notebook via email?

Thanks in advance!

__

FA

POSTED BY: Fabio Alcaro

@Fabio Alcaro , Yes please email the notebook to wolfram-u@wolfram.com

Thanks

Posted 2 years ago

I missed the Survey at the end of today's session. My request for tomorrow's Review session is to look a bit into string replacements using patterns. Do we have to use Regular Expressions at times, or can we do the same with patterns?

Cheers,

Dave

POSTED BY: Dave Middleton

You can do a lot even without Regular Expressions. You will have to use dedicated functions to work with string patterns like StringReplace, StringMatchQ, StringContainsQ etc. You will find them listed here and you can use this tutorial to get started.

Posted 2 years ago

Hi. If I define an uppervalue x by: x /: _[x] = 0, How can I clear it?

POSTED BY: Jin Zhang

I suppose you want to clear ONLY a specific upvalue otherwise Unset or Clear would have been fine. You can use TagUnset.

In[1]:= sq /: area[sq] = s^2;
sq /: circ[sq] = 4 s;

In[2]:= sq /: circ[sq] =.

In[3]:= {area[sq], circ[sq]}

Out[3]= {s^2, circ[sq]}

I found another user try to do something similar here: https://community.wolfram.com/groups/-/m/t/1072731

Posted 2 years ago

Hi Abrita, Thanks for your reply. I want to clear x specifically defined as this and say I want to clear x and used it in other things, such as Sin[x]. Clear[x] and Unset[x] will match the pattern and return 0, so cannot clear x.

In[1]:= x /: _[x] = 0    
Out[1]= 0    
In[2]:= Clear[x]
Unset[x]    
Out[2]= 0    
Out[3]= 0
In[4]:= Sin[x]
Out[4]= 0
POSTED BY: Jin Zhang

@Jin Zhang I reached out to our instructor Dave Withoff for further help on this. Below I have posted Dave's suggestion:

This particular rule for x can be cleared using Clear[x,x] or Clear["x"].

For example:

In[1]:= x /: _[x] = 0
Out[1]= 0
In[2]:= Clear[x]
Out[2]= 0
In[3]:= Clear["x"]
In[4]:= Sin[x]
Out[4]= Sin[x]

Clear[x,x] would also work because that upvalue for x only applies to expressions with one argument x, and so that rule doesn't apply to Clear[x,x].

Clear["x"] clears any symbols with names that match the string pattern "x".

The basic problem, as you presumably noticed, is that the upvalue for x gets applied to anything of the form _[x], including Clear[x], and since upvalues get applied before downvalues, and since Clear[x] works using a downvalue for Clear, this makes it difficult to clear the rule for x.

Clear["x"] works because, although the string "x" gets converted to the symbol x within the Clear function, that conversion doesn't happen until after the downvalue for Clear is already being applied, and the Clear function clears the rule for x in a way that does not involve evaluating Clear[x].

More generally, this is an example of one of a small handful of inputs in the Wolfram Language that can be difficult to undo. These things almost never come up in practical applications, but they do sometimes come up by accident, or sometimes they come up when just trying things out to see what will happen.

For example, I do not recommend evaluating:

$Pre = Function[x, Pause[600]; x, HoldAll]

which will introduce a ten minute pause before every evaluation. The pause can be aborted, but it is difficult to remove that pause without waiting ten minutes for a subsequent evaluation to remove it.

It is unlikely that such a thing would be entered by accident, of course, but if a predicament arises where something that is difficult to undo has happened, a general solution is to quit the Wolfram Language session and start over.

Posted 2 years ago
POSTED BY: Jin Zhang
Posted 2 years ago

In today's study group's "Exercises for Image Processing", Exercise 1. the code provided does not work on my Windows 10 21H2 machine with Mathematica version 13.0.1.0 i.e. the 2D slider t2 doesn't do anything.

img = Binarize[
   Graphics[{Disk[{0, 0}, 8], White, Disk[{0, 0}], Disk[{2, 2}]}, 
    ImageSize -> 200]];
Manipulate[
 ImageResize[ImageTrim[img, {t1, t2}], 
  400], {t1, {1, 1}, {177, 177}, {1, 1}, 
  Appearance -> "Labeled"}, {{t2, {400, 400}}, {271, 271}, {400, 
   400}, {1, 1}, Appearance -> "Labeled"}, ControlPlacement -> Left]

Is this an issue on my end or is this a bug? If the latter, is there a work-around?

Cheers,

Dave

POSTED BY: Dave Middleton
Posted 2 years ago

Dave I have a similar setup to you and its working fine on my machine ( I tend to forget to set the "dynamic Update Enabled " under the evaluation menu and at times my Mathematica resets this while running code )

POSTED BY: Doug Beveridge
Posted 2 years ago

Thanks Doug. The "Dynamic Updating Enabled" is on, or else the t1 2D slider wouldn't work either. Maybe my installation is corrupted somehow.

POSTED BY: Dave Middleton

Hi Dave, Does a simple 2DSlider work for you?

Slider2D[{.7, .3}]
Posted 2 years ago

After spending some time problem solving, it's not an issue with the t2 slider after all. If I do:

img = Binarize[
   Graphics[{Disk[{0, 0}, 8], White, Disk[{0, 0}], Disk[{2, 2}]}, 
    ImageSize -> 200]];
ImageTrim[img, {{177, 177}, {271, 271}}]

The result is a white image of 24 x 24 pixels, not the picture in the Exercise solution. For some reason the code does not work with this image on my system, which I am not going to explore further.

If I replace the image by Dave's balloon image in the Lesson 27 notebook, all works fine.

At least, as an additional exercise I spent some time with sliders, Manipulate and even DynamicModule :)

POSTED BY: Updating Name
Posted 2 years ago

Quiz 2, problem 4 (please do not discuss solutions, just a meaning of the word): what is the meaning of "where" in "where evaluation can still be done"?

POSTED BY: Updating Name

Quiz 2, Problem 4, answer option A says "Displays a dialog box with the message 'Click OK', where evaluations can still be done without dismissing the dialog box", i.e. you can continue to evaluate further code in the notebook, without dismissing the dialog box.

Dave Withoff suggests the following: XOR matrix multiplication is defined differently in different contexts, but a typical definition can be computed using the Inner function, as in

In[]:= x = {{1, 1, 1}, {1, 1, 1}, {0, 0, 0}};
In[]:= y = {{0, 0, 1}, {1, 0, 1}, {0, 1, 1}};
In[]:= Inner[BitXor, x, y, BitOr]

Out[]= {{1, 1, 0}, {1, 1, 0}, {1, 1, 1}}

which shows XOR matrix multiplication defined as matrix multiplication with bitwise XOR in place of multiplication and bitwise OR in place of addition.

Other definitions can be computed using combinations of logical functions, bitwise logical functions, and matrix operations like Inner and Outer.

Posted 2 years ago

Thanks Abrita

Inner[ Times, x, y,  BitXor ]

is the solution

POSTED BY: Updating Name
Posted 2 years ago

What is the most efficient way to do XOR matrix multiplication?

Attachments:
POSTED BY: Doug Beveridge
Posted 2 years ago

I am not entirely clear about this behavior of Interval[ ]:

POSTED BY: lara wag

@lara wag please find below the response from Dave Withoff:

This is a common generic problem in propagation of uncertainty that I first (several decades ago) saw referred to as "The Problem of All Errors Being Treated as Independent".

The result from b-b, for example, could reasonably be expected to be zero, since b-b is zero for any number b, and this is obviously true even if b is a number chosen from an interval.

That, however, is not how the calculation is done, or how propagated errors are typically calculated. If b is an interval, say, for example, Interval[{1,5}], then b-b becomes Interval[{1,5}] - Interval[{1,5}] and the calculation is done by working on the range of possible answers for any number in the interval {1,5} minus any other number also in the interval {1,5}, without the restriction that the two numbers have to be the same number.

This is a very common issue in numerical analysis, specifically in working out accumulated error in numerical algorithms. Parameters that come up in numerical algorithms almost always occur in lots of places within the numerical calculation. If those parameters have some uncertainty, the uncertainty in the result is overestimated if the values of the parameter are treated as different independent values everywhere that each parameter occurs.

Although a better error estimate can be obtained by recognizing that the value of a parameter is always the same, even if that value might be uncertain, this makes the propagation of error calculation so much more difficult that it is usually done only in limited examples. It is not typically done in results from functions like Solve.

In the result from

In[]:= Solve[x^2 + b x == 6, x][[2]]

Out[]= {x -> (1/2)*(-b + Sqrt[24 + b^2])}

for example, the parameter b occurs in two different places. If that parameter is replaced by Interval[{1,5}] the result is

In[]:= {x -> (1/2)*(-b + Sqrt[24 + b^2])} /. b -> Interval[{1, 5}]

Out[]= {x -> Interval[{0, 3}]}

which is the result returned by Solve. For any value of b in the interval {1,5} that solution is always between 1 and 2, so the result could instead be Interval[{1, 2}]. The actual interval returned by Solve is bigger because the two appearances of b in the result are treated as independent.

Posted 2 years ago

Thank you very much, Abrita and Dave!

I would never have thought of that...

POSTED BY: lara wag

In my previous post I used the function SolveValues. Please note its naming inconsistency with DSolveValue and NDSolveValue. Why is one plural while the others are singular? Shouldn't, perhaps, for naming consistency, a SolveValue version be added to WL? (obviously we have to keep SolveValues now that a number of already written programs are using it).

POSTED BY: Zbigniew Kabala

I must confess that I am totally confused about the concept of precision in Mathematica / Wolfram Language. Let me share this confusion with you:

POSTED BY: Zbigniew Kabala
Posted 2 years ago

@Zbigniew: In my bookshelf I have the book "Numerical Methods that (usually) work" by F. Acton. This book is technically very good, although the topics are not up-to-date anymore (at least if you use Mathematica...).

Between part 1 and 2 there is an intermediate chapter, it is called "Interlude: What not to compute". It is great fun to read this and it begins as follows:

Do you ever want to kick the computer? Does it iterate endlessly on your newest algorithm that should have converged in three iteration? And does it finally come to a crashing halt with the insulting message that you divided by zero? These minor trauma are, in fact, the ways the computer manages to kick you and, unfortunately, you almost always deserve it!

I always feel caught when I read this... :-)

POSTED BY: lara wag
Posted 2 years ago

Thank you Lara for cheering me up. But I'm still ready to let gravity take its course ... :)

POSTED BY: Updating Name
Posted 2 years ago

Hi Zbigniew,

I think all of your questions are related to the fact that by default the frontend only shows 6 digits for MachinePrecision values, irrespective of what precision values is passed to N.

sol // InputForm
(* {-3.035090330572526, 1.0350903305725259} *)

This can be changed, e.g.

(* For the current frontend session *)
SetOptions[$FrontEndSession, PrintPrecision-> 16]

(* For the current and future frontend sessions *)
SetOptions[$FrontEnd, PrintPrecision-> 16]

(* For the current notebook *)
SetOptions[InputNotebook[], PrintPrecision-> 16]

Or you can use NumberForm.

NumberForm[sol[[1]], 16]
(* -3.035090330572526 *)
POSTED BY: Rohit Namjoshi

@Zbigniew Kabala, Here is Dave's response to your questions:

Posted 2 years ago

Thank you for the thourough explanation.

POSTED BY: Updating Name

The problem of squaring an interval was left kind of open. Here is an explanation.

POSTED BY: Zbigniew Kabala
Posted 2 years ago

The Wolfram Function Repository contains a TruthTable function; see attached file "TruthTable-1-0-0-definition.nb". In addition, I've written my own truthTable module that converts an input Boolean expression into disjunctive normal form (DNF) and provides this as a header in the output truth table. My code and comments are in attached file "GDorfman_TruthTableModule.nb". I'd appreciate suggestions for how to test the input expression to determine if it is a well-formed Boolean expression.

POSTED BY: Gerald Dorfman
Posted 2 years ago

Thanks for your response to the Print issue I posted. The CellPrint code you provided works well. Based on that, I went back to the Print Help. My take on that is that Print generates something like CellPrint, though my attempt to use FullForm[HoldForm[Print[...]]] did not work. How does one find what the underlying Wolfram Language code of Print is or is Print just a function unto itself? That is, how do I find out whether Print is using CellPrint?

Since Print has no options, I tried Grid with Frame -> True, which shows that the width is set to that of the wider of the two lines of text. This suggests that at least part of the Print problem may have to do with cell width being set this way. To fix this, I added to Grid the option ItemSize. Here is the code, which works fine:

Grid[{{Style["Options for Plot and ListPlot", Bold, 16, 
Orange]}, {Style["Options in Common", Italic, 14, Blue]}}, 
Alignment -> Center, Frame -> True, ItemSize -> 50]

Attached file "GDorfman_GridToCenterText.nb" has the above code with and without ItemSize along with the corresponding output.

Attachments:
POSTED BY: Gerald Dorfman
Posted 2 years ago

If you create DockedCells

eg enter image description here

How do you remove it ?

POSTED BY: Doug Beveridge
Posted 2 years ago

Doug,

To remove all docked cells

SetOptions[EvaluationNotebook[], DockedCells -> {}]
POSTED BY: Rohit Namjoshi

Input NRoots[x^2 == 5, x]

gives me an error: ... General: 5 is not a valid variable.

What's wrong?

Try evaluating x by itself and I think you'll see where the Irishman comes from :). Run ClearAll[x] after that and NRoots will do its job as expected.

POSTED BY: Arben Kalziqi

Thank you!

Posted 2 years ago

I was delighted to learn how fancy Mathematica is regarding integrating over regions. Yesterday's lecture (April 28, 2022) illustrated some really cool things that got me excited. I played around with some examples, for the fun of it. This is a really nice ability. I am including the notebook with 2 neat examples. Oddly there might be a bug, although the "bug" is probably mine. It is amazing that one can integrate over such exotic regions.

See the attached notebook.

Attachments:
POSTED BY: George Schils
Posted 2 years ago

I feel like I am doing something exceedingly stupid, but am having trouble getting the volume of a sphere as given below.

enter image description here

This calculation gives 7.06858347057703478654094869079, which is off by a factor of 4.

POSTED BY: George Schils

Try Ball instead of Sphere—despite colloquial usage, a sphere is a 2D object that embeds into 3D space.

POSTED BY: Arben Kalziqi
Posted 2 years ago

Arben, thank you for your kind response. Indeed, the use of Ball in place of Sphere makes everything work wonderfully. I went on to play around with some cool and fun examples, and I am including the updated notebook. Here is a highlighted example from the attached notebook, where it finds a closed form solution. enter image description here

POSTED BY: George Schils

I'm glad to hear it! I might be biased, but I do think it's pretty cool that you're able to achieve such a result. Also—while this may be a bit trivializing in some sense, we really do have a function for everything! Try out RegionMeasure, if you'd like, e.g.: Manipulate[ RegionMeasure /@ {Disk[{0, 0}, d], Sphere[{0, 0, 0}, d], Ball[{0, 0, 0}, d], Cuboid[{0, 0, 0}, d {1, 1, 1}]}, {d, 1, 5, 1}] This can be useful to provide some insight which is relevant to the dimensionality question we're discussing (somewhat paradoxically). On a related note, you might try something like Volume[Sphere[]] and get a (previously-)surprising result.

Or, you could make the variation continuous, then Plot to see the problem another way: Plot[Evaluate[ RegionMeasure /@ {Disk[{0, 0}, d], Sphere[{0, 0, 0}, d], Ball[{0, 0, 0}, d], Cuboid[{0, 0, 0}, d {1, 1, 1}]}], {d, 1, 5}, ScalingFunctions -> {"Log", "Log"}] (adding PlotLegends->"Expressions" would make it explicit, to wit.)

EDIT: I'd be loathe to forget RegionDimension!

POSTED BY: Arben Kalziqi
Posted 2 years ago

Arben, thank you for your additional comments (BTW, which were made on a Saturday), which I am now beginning to work on. I wanted to dash off a quick note as I am just up on this Sunday and have just taken the first sip of coffee.

To wit: I am more than biased regarding Mathematica. I am dazzled by the cool things that you can do with it. It is amazing that one can measure the volume of such incredible regions in 3-space. It is amazing that it finds a closed form solution in terms of elliptic functions for one of the volumes in my last note. This also works in 4-space and more. Recently, following the documentation, I did an integral in 1000 dimensions. (An interesting problem is defining the integrand here.) It is not unusual for me to spend hours, sometimes more than 12, "just" studying the documentation. Mathematica does so many amazing things.

I am going to play around with RegionMeasure some, as you suggested. I am sure it is a much better implementation than my own regionIntegrate3D (see included notebook) that I had concocted just to play around, to practice, to hone skills, etc. I note that this is recreational mathematics. I am doing this for fun, but also hope it might lead to something wonderful. My apologies for not being better than I am at Mathematica: I have loved it since VERSION ONE (circa 1987 or so). For someone who has used it a long time, I should be better at it. I am spread very thin pursuing many interests, especially including music and photography.

To play around with (tagged) upvalues, I might try to play with a concept similar to the class example "n g[x] expanding to g[n x]". While laying in bed this morning, I thought about something like 3 h[Ball[]] creating 3 balls. This can generalize nicely. If it sees n g[x] as a pattern, maybe it will see {point1,point2,n} * h[Ball[]] as an upvalue for h, and then construct n Balls from point1 to point2, but only if the symbol h is used. This is just fantasy (fantasia) now, but I might want to play around with this.

POSTED BY: George Schils
Posted 2 years ago

Additional notes on this comment from above.

"If it sees n g[x] as a pattern, maybe it will see {point1,point2,n} * h[Ball[]] as an upvalue for h, and then construct n Balls from point1 to point2, but only if the symbol h is used."

I want to create a simple "extension" using tagged delayed assignments (up values) to allow n points to be enumerated over a line from point1 to point2. We try this naively and find that the implicit multiply operation is listable, so we get a list of the multiplied values.

In[150]:= ClearAll[g]
g /: n_List g[x_] := g2[g1[n], x]
{point1, point2, n} g[x]

Out[152]= {point1 g[x], point2 g[x], n g[x]}

This is not what we want. Instead of using the Times[] function, we will use h, which is not listable, in the above instead.

In[144]:= ClearAll[g]
g /: h[n_List, g[x_]] := g2[g1[n], x]
h[{point1, point2, n}, g[x]]

Out[146]= g2[g1[{point1, point2, n}], x]

g1 can be a function to generate the n points and then it is passed to g2 which does the volume rendering of x. Maybe there is an existing function for this, but this is a fun exercise anyway.

Basically, we are recognizing a certain context involving an outer scope of the function g, and then doing something special to it when we recognize it. This is an amazing ability! WOW!

I learned a lot in writing this stuff up. Tagged delayed assignments are really cool, and I had fun playing with the concepts which I had just recently learned.

POSTED BY: George Schils
Posted 2 years ago

I am adding to the ""If it sees n g[x] as a pattern" from above.

Using a tagged delayed assignment to generate a list of volumes along a line

Two relatively simple lines of code make it easy to generate volume objects along a straight line.

LinePoints[{p1_, p2_, n_}] := Table[p1 + (p2 - p1) k/n, {k, 0, n}];
UsingA /: GenerateLinearRegion[n_List, UsingA[x_]] := 
 Region[RegionUnion[Map[x[#] &, LinePoints[n]]]]

Here UsingA is a tagged delayed assignment. Its use makes it easy to generate volumes. For example

GenerateLinearRegion[{{0, 5, 0}, {15, 0, 0}, 10}, UsingA[Ball]]

generates a series of 11 Ball objects from {0,5,0} to {15,0,0}, and is shown below.

enter image description here

Another example is here.

enter image description here

A more complex structure is also easy to generate.

enter image description here

These examples are from the attached notebook, which includes more illustrations.

The tagged delayed assignment is a really cool feature of WL.

Attachments:
POSTED BY: George Schils
Posted 2 years ago

I have added more cool examples on neat regions that can be generated using the GenerateLinearRegion UsingA methodology of a previous post. An exotic region is depicted below.

enter image description here

I also have added some things that alternatively work within the context of the + operator.

DrawLineOf[Ball] + From[{0, 0, 0}] + To[{5, 0, 0}]

This generates the same image as above. Because + is orderless, the items can appear in any order.

enter image description here

In fact we don't need the + above, and if we leave it blank it will use Times instread of Plus.

From[{0, 0, 0}] DrawLineOf[Ball] To[{5, 0, 0}]

This creates the same line of balls as above.

There is more discussion in the notebook.

Sorry for all the verbosity, but I am finding it hard not to work on this. In addition to finding the volume measure of these regions, it is even more amazing that in WL these regions can be integrated over (perhaps with a wave function as the integrand) or used as region constraint areas for numerical optimization problems.

POSTED BY: George Schils
Posted 2 years ago

I am repeating this calculation using RegionMeasure. It is totally amazing that Mathematica finds a closed form solution!!! Don't complain if it takes a few minutes -- wanna try it by hand?? haha.

enter image description here

POSTED BY: George Schils
Posted 2 years ago

Expanding on your comments, Arben, we see indeed that integrating using Sphere vs. Ball clearly gives different answers.

In[6]:= Integrate[1, {x, y, z} \[Element] Sphere[]]

Out[6]= 4 \[Pi]

In[7]:= Integrate[1, {x, y, z} \[Element] Ball[]]

Out[7]= (4 \[Pi])/3

Using RegionMeasure allows the dimension of the integration to be specified.

In[8]:= RegionMeasure[Sphere[]]

Out[8]= 4 \[Pi]

Agreeing with your comment, Arben, Sphere[] is 2-dimsional, and its 3-D measure gives zero. WOW - that's a gocha.

In[10]:= RegionMeasure[Sphere[], 3]

Out[10]= 0

Note the correct answers using Ball[] below.

In[9]:= RegionMeasure[Ball[]]

Out[9]= (4 \[Pi])/3

In[11]:= RegionMeasure[Ball[], 3]

Out[11]= (4 \[Pi])/3

As a final note, we see and understand the next result.

In[12]:= RegionMeasure[Ball[], 4]

Out[12]= 0
POSTED BY: George Schils
Posted 2 years ago

More comments regarding Ball and Sphere

I am not claiming that there is an error here, only just misuse and misunderstanding (by me) of an understandably tricky point. We have the same issue regarding Circle[] and Disk[]. Circle is the 1 dimensional circle (circumference) whereas Disk[] is the filled 2 dimensional object. We see this in the following three calculations. The circumference of the unit circle is 2 Pi.

In[121]:= RegionMeasure[Circle[]]

Out[121]= 2 \[Pi]

In[124]:= RegionMeasure[Circle[], 1]

Out[124]= 2 \[Pi]

In[122]:= RegionMeasure[Circle[], 2]

Out[122]= 0

In[123]:= RegionMeasure[Disk[], 2]

Out[123]= \[Pi]

Now, with Disk[] we find the area of the unit circle or Pi. These results all make sense.

We have a similar situation regarding Sphere[] and Ball[].

The RegionMeasure of the Sphere[] is its 2-dimsional surface area, which is 4 Pi, whereas the RegionMeasure of Ball[] is its 3-dimensional volume, which is 4 Pi/3.

In[126]:= RegionMeasure[Sphere[], 2]

Out[126]= 4 \[Pi]

In[127]:= RegionMeasure[Sphere[], 3]

Out[127]= 0

In[128]:= RegionMeasure[Ball[], 3]

Out[128]= (4 \[Pi])/3

This all makes sense, now, but this is an easy point to get tripped up over. Arben, thanks for bringing this to light! Clearly, this is not an error, and it should be this way, but this is definitely a very subtle point.

POSTED BY: George Schils
Posted 2 years ago

Looking for a possible application for upvalues, I made the following definition:

f[x_ /; x < 1] := 1;

f[x_ /; x >= 1] := x x x;

Sqrt[f[x_] /; x >= -2 && x <= -1 ] ^:= 3;

If I now want to test the effectiveness of my definition by calculating a square root of f[-1.5], it does not seem to work at first glance:

Sqrt[ f[-1.5]] returns 1, and not the expected 3.

The same applies to a function plot:

Plot[Sqrt[ f[x]], {x, -5, 5} ]

On closer analysis, it turns out that the calculation first calculates the inner term, and the kernel then forgets that the inner value arose by evaluating f[x], and accordingly does not apply the upvalue.

If I forbid the evaluation of the inner term, we get the expected results:

Sqrt[ Unevaluated[ f[-1.5]]]

Plot[Sqrt[ Unevaluated[f[x]]], {x, -5, 5} ]

This shows me that upvalues do not allow the overloading of functions similar to OOP that I had hoped for. Always thinking about disallowing the evaluation of the inner term limits the usability in my eyes.

However, this begs the question. What is a real life use case for the upvalues?

POSTED BY: Peter Lippolt

@Peter Lippolt here is an explanation from the instructor Dave Withoff

The essential issue raised by the example

In[]:= f[x_ /; x < 1] := 1
In[]:= f[x_ /; x >= 1] := x x x
In[]:= Sqrt[f[x_] /; x >= -2 && x <= -1] ^:= 3

In[]:= Sqrt[f[-1.5]]
Out[]= 1

is the question of what the system should do when two rules apply to the same input, rather than a specific feature of upvalues.

The problem is that the rule for f[x_ /; x < 1] and the rule for Sqrt[f[x_] /; x >= -2 && x <= -1] both apply to Sqrt[f[-1.5]]. Without further information, the computer has no way of knowing which rule to use.

In the Wolfram Language, the default, following the principle of standard order evaluation (evaluating the elements of an expression before evaluating the enclosing expression), is to evaluate f[-1.5], which has the effect of applying the rule for f[x_ /; x < 1].

There are many ways to get the rules applied in a different order. One method is to enter all of the rules as upvalues for f:

In[]:= Sqrt[f[x_] /; x >= -2 && x <= -1] ^:= 3
In[]:= f /: _[f[x_ /; x < 1]] := 1
In[]:= f /: _[f[x_ /; x >= 1]] := x x x

In[]:= Sqrt[f[-1.5]]
Out[]= 3

Entering all of the rules as upvalues like this is closer conceptually to the way this would work in an OOP system. Mixing upvalues and downvalues potentially increases confusion about which will be used first.

A few observations about this behavior:

1) Comparable issues will arise in any system, including OOP systems. If two rules, or two methods, apply in the same situation, the computer has to somehow resolve the conflict. Different systems will handle the conflict in different ways, but the conflict will remain.

2) Conflicts like this are rare in practical applications. It is easy to make up examples where the system is presented with ambiguous instructions and has to follow some default or some process for deciding what to do, but in practical applications such ambiguities usually either don't come up in the first place, or are resolved in some other way.

3) To address the question about real-life uses of upvalues, there are a number of large applications of upvalues. Two prominent examples are the rules for series expansions, and implementation of non-commutative algebra.

The built-in rules for series expansions are implemented as upvalues for SeriesData. SeriesData is the symbol that is used for representing series expansions. For convenience of programming, the rules for series expansions are implemented as upvalues for SeriesData rather than as downvalues for individual functions.

For example, Series[Exp[x], {x, 0, 3}] is evaluated by first constructing SeriesData[x, 0, {1}, 1, 4, 1], which is the series expansion to degree 3 for x by itself, and then applying Exp to that SeriesData expression. The result is normally formatted as a sum, but the SeriesData expression can be seen using InputForm:

In[]:= Exp[SeriesData[x, 0, {1}, 1, 4, 1]] // InputForm

Out[]//InputForm= SeriesData[x, 0, {1, 1, 1/2, 1/6}, 0, 4, 1]

The rules that gave that result, and the rules for doing series expansions of other functions, are implemented as upvalues for SeriesData. Comparable rules could be entered as downvalues for individual functions, such as the Exp function, but it is easier to do the programming if all of the rules for series expansions are in one place, attached to SeriesData, rather than scattered throughout the system among all of the other rules for individual functions.

Similarly, it is convenient when entering rules for non-commutative algebra to attach rules as upvalues for elements of the algebra. For example, using the ** notation for NonCommutativeMultiply:

In[]:= x /: x[p_] ** x[q_] := -x[q] ** x[p] /; ! OrderedQ[{p, q}]

In[]:= x[2] ** x[1]

Out[]= -x[1] ** x[2]

A comparable rule could have been entered by unprotecting the built-in symbol NonCommutativeMultiply and entering a downvalue for NonCommutativeMultiply, but some consider it easier or more natural to instead enter a rule like this as upvalue for x.

Posted 2 years ago

The first two Print statements below center the text. The third Print statement, which just combines the first two, does not center the text. Attached file "GDorfman_PrintIssue.nb" shows the three Print statements and their output. Why does the third Print statement not center the text? How can it be modified so it does center the text?

Print[Style["Options for Plot and ListPlot",Bold,16,Orange,TextAlignment->Center]]

Print[Style["\nOptions in Common\n",Italic,14,Blue,TextAlignment->Center]]

Print[Style["Options for Plot and ListPlot",Bold,16,Orange,TextAlignment->Center],
Style["\nOptions in Common\n",Italic,14,Blue,TextAlignment->Center]]
Attachments:
POSTED BY: Gerald Dorfman
Posted 2 years ago

The documentation for Print says:

  • Print[Subscript[expr, 1],Subscript[expr, 2],[Ellipsis]] prints Subscript[expr, i] concatenated together, effectively using Row
  • You can arrange to have expressions on several lines by using Column. 

So the output I see is the same as what the following provides:

Row[{
  Style["Options for Plot and ListPlot", Bold, 16, Orange, TextAlignment -> Center], 
  Style["\nOptions in Common\n", Italic, 14, Blue, TextAlignment -> Center]
  }, Alignment -> Right]

The Alignment option does not quite center the output within the output cell. The best I could come up with was:

Print[
 Column[{
   Style["Options for Plot and ListPlot", Bold, 16, Orange, 
    TextAlignment -> Center], 
   Style["\nOptions in Common\n", Italic, 14, Blue, 
    TextAlignment -> Center]
   }, Alignment -> Center]
 ]

Even this does not produce the output that you probably want.

However with Print ultimately creating a "cell", I wondered why not just use CellPrint that is supposed to insert a cell in the current notebook. So here is what I have:

CellPrint[
 {
  TextCell[Style["Options for Plot and ListPlot", "Output", Bold, 16, Orange, TextAlignment -> Center]], 
  TextCell[Style["Options in Common", "Output", Italic, 14, Blue, TextAlignment -> Center]]
  }
 ]

This output seems more like what you want to see.

POSTED BY: Updating Name

[WSG22] Daily Study Group: A Guide to Programming and Mathematics with WL

Abrita,

Many thanks.

The notebook for Friday's lesson (#19) appears to be missing. When will it be made available?

Notebook 19SolvingEquations.nb has now been added.

Is there a way to prevent Mathematica from inserting spaces into a URL I put in a notebook?

If I copy a URL into Mathematica, then copy it from there, it comes out like this:

https : // www . wolframalpha . com/input?i = Table %5 BExpand %5 B %28 Power %5 BGoldenRatio %2 Cn %5 D + -+Power \ %5 B %281 + -+GoldenRatio %29 %2 Cn %5 D %29 %2 FSqrt %5 B5 %5 D %5 D \ %2 C + %7 Bn %2 C + 0 %2 C + 18 %7 D %5 D

Hi Thomas!

When pasted as text, there are no spaces. So, format the cell as text first, then past.

Have fun!

POSTED BY: Lori Johnson

As @Lori Johnson mentions, if you paste a URL into a text cell it will be pasted correctly and even change into a hyperlink. You can create a text cell in a notebook as shown here: https://reference.wolfram.com/language/workflow/CreateATextCell.html

Posted 2 years ago

My congratulations to Abrita Chakravarty with splendid and so useful work during all this daily group! Great efforts, thank you.

Could you (or someone else) give a clue concerning quizes? As far as I remember, we should have two of them at this week. What is a way to get the quizes? Or, perhaps, it is too early to ask (my apologies then).

POSTED BY: Olga Pavlova

Thank you @Olga Pavlova

We are in the process of getting the quizzes ready for release. We hope to share a link to the first quiz by the end of the week. We will share it in the live session and also include it in reminder emails.

Hi Abrita! Thank you, Abrita, and everyone working to put them together!

POSTED BY: Lori Johnson

Q&A transcript from Day 5 of Week 1 has been added to the download folder. We'll add the digest from this week at the end of the week.

Posted 2 years ago

In session 16, Symbolic Mathematics, I modified some code in subsection "Root Expressions" to get a legend on the plotted output. My modified code is:

In[24]:= sol=Solve[x^8+ x+b==0,x]
Plot[Abs[x/.sol],{b,-5,5},PlotRange->All,PlotLegends->Automatic]

Here is the output of the first line of code:

Out[24]= {{x->Root[b+#1+#1^8&,1]},{x->Root[b+#1+#1^8&,2]},{x->Root[b+#1+#1^8&,3]},{x->Root[b+#1+#1^8&,4]},{x->Root[b+#1+#1^8&,5]},{x->Root[b+#1+#1^8&,6]},{x->Root[b+#1+#1^8&,7]},{x->Root[b+#1+#1^8&,8]}}

The second line of code includes my added option "PlotLegends->Automatic" but it does not result in any legends. I guess the reason has to do with the form of Out[24] which is the value assigned to sol. Please explain why "PlotLegends->Automatic" doesn't work here and what code will generate legends in the Plot.

Attached as file GDorfmanPlot_26apr22.nb is a copy of the graph in which I have interactively colored the curves representing the absolute values (i.e., lengths of the complex values) of the solutions as functions of b. There are 4 rather than 8 curves. I assume this is because the solutions come in conjugate pairs.

POSTED BY: Gerald Dorfman
Posted 2 years ago

Something like this?

Plot[Evaluate[Abs[x /. sol]], {b, -5, 5},
 PlotRange -> All,
 PlotStyle -> ColorData[3, "ColorList"],
 PlotLegends -> "Expressions"]

enter image description here

POSTED BY: Rohit Namjoshi

@Thomas Ray Worley please feel free to email wolfram-u@wolfram.com if you are facing issues with the notebooks. We will be happy to help you troubleshoot further. You should be able to open all the notebooks in the same way.

Week 1 Review notebook added to download folder.

Thanks Richard. That second reason should always be kept in mind.

Thanks Richard.

It appears that f[x_] := f[x] =. .. is more efficient. Is there ever a case in which it should not be used?

Posted 2 years ago

You would probably not want to use this if the function was unlikely to be frequently called with the same argument. You would DEFINITELY NOT want to use it if you need the function to return different results when called with the same argument (e.g. if the result depended on some extermal value such as the current time or any of the Random* functions).

POSTED BY: Richard Hewens

Thanks for the response and explanation, @Richard Hewens

SetDelayed OR Set should serve well in defining a function.

Here is an example of where using Set and SetDelayed together is helpful and might explain why it would be not advisable to try and use them together ALL the time.

In the following example, when the need arises to store some constant values, immediate assignments are made. On the other hand, to store a more generic definition of the function, delayed assignment is used:

fib[0] = 0;
fib[1] = 1;
fib[n_] := fib[n] = fib[n - 1] + fib[n - 2]

The use of both Set and SetDelayed allows assignments to be made dynamically:

?fib

The Wolfram Language provides automatic recursion, coded into the delayed assignment definition of fib[n_]. Each time a new n is used, a new value for the function fib is defined and stored away. This avoids having to return all the way to the base case for every value that is used:

fib[3]

?fib

Trace[fib[4]]

Clear[fib]

When defining functions, when is it better to use f[x_] := f[x] =. ..instead of just f[x_] := ...? Why?

Posted 2 years ago

When using the "f[x_] := f[x]=...", this is creating a more specific function with the same name (which will be called before the original f[x_] form). This is most useful when the function will be called multiple times with the same argument, is which case the computation will only need to be done once.

POSTED BY: Richard Hewens
Posted 2 years ago

Can someone explain this curious behavior of the Defer function:

Defer[Plus[0, 1, 2, 3, 4, 0, 1, 2, 3, 4]] results in 0 + 1 + 2 + 3 + 4 + 0 + 1 + 2 + 3 + 4, but
Defer[Times[0, 1, 2, 3, 4, 0, 1, 2, 3, 4]] results in 0 x 2 x 3 x 4 x 0  x 2 x 3 x 4

It appears that Defer somehow "knows" that any 1's can be removed from a product without affecting the result (but doesn't remove the 0s from a sum) . My first thought was that Plus and Times might have different attributes, but they were identical. Any clues to what's going on here will be appreciated.

POSTED BY: Richard Hewens

Hi Richard—I'm looking into this. For the time, I can note that it's not a property of Defer, since Hold and Unevaluated (at least) do the same thing. The current thought is that it's a formatting property of Times, and formatting is a bit of an arbitrary choice that language designers have to make. I do agree that it's strange that the additive identity does not format the same way for Plus, though.

POSTED BY: Arben Kalziqi

Bravo, Richard. You have a sharp eye. Not everyone would have noticed this nuance.

Based on my previous experience ( about 6 classes taken at different times), I would recommend the following.
(1) Create a notebook, say "Class3_my practice and questions". Let's call it MNB (my notebook).
(2) Open the downloaded class notebook(s), typically one or two (CNBs).
(3) The goal is to reproduce in MNB the most of activities presented in CNBs. Also, consider some variations of the offered examples, mark the difficulties and formulate the questions.
(4) In doing so, make sure to create sections in MNB ( using Alt-1 - Alt-6 shortcuts, with textual inserts using Alt-7) reflecting the corresponding sections in CNBs (so that the general structure of MNB is similar to CNB, but it may include some additional sub(-sub)sections such as "My question to the forum", or "some additional examples", or "the definition of such and such function...").
(5) Watch the pieces of the class video addressing the questionable parts (in case you do not have time to watch the whole video).
(6) As a result, you should have a few unanswered questions. Never hesitate to post them on the forum. This is good for all the participants! So, consider it a public service :)
(7) In parallel, create the notebooks Quiz1, 2, etc for solving the quiz problems. Each lecture contains (hints to) the answers to some Quiz questions. Doing it continually makes the Quiz activities less stressful (make sure not to discuss directly the Quiz questions on the forum, but you can discuss any related general issues ).

Good luck.

very nice.

POSTED BY: Sanjit Das
Posted 2 years ago

This is really helpful - thank you!

POSTED BY: D Groves

Please post more 'stackoverflow'-like post like this in the future... it benefits a LOT.. on a very LONG run..

Posted 2 years ago

Thank you. :-) Class is going a bit rapidly. Consequently, I like to work the notebooks and exercises after class in the evening to reinforce my learnings. I am very much enjoying the classes, but there are so many new ideas and insights every day that it takes some time and practice to internalize the use and application of all the tools we have been exposed to. What is the best way to get more practice?

POSTED BY: D Groves
Posted 2 years ago

With more than 24 new functions per second, one probably has to assume a movie. Nevertheless, the study group is absolutely fascinating, and offers many new insights.

POSTED BY: Peter Lippolt

Responding to multiple-choice Qs does not contribute to certification. It's for self-testing. Watching the lectures and passing the quizzes do.

That is correct. Thanks Michael.

The requirement for certificate of Program Completion for the study group is attending the live sessions and passing the online quizzes with a score of at least 60%. We will release 3 quizzes over the entire duration of this 3-week study group and you will have time till may 13th to complete all the quizzes.

I need to regroup for a trip that starts Monday. For that time I will switch to a cloud account and need to arrange file directories. (1) How to (up)load their files for the class? (2) How to order them based on the sessions' order number? . The ordering turned out to be especially ticky. Thank you

Posted 2 years ago

Hi, I can watch the lectures as a recorded video. Is there an another way to get certificate of progtam completion rather than solving multiple choices problems on live sessions?

POSTED BY: Hasan SANSAR
Posted 2 years ago

Are we able to get copies of the exercises so we can work them offline to ensure we understand? Thank you!

POSTED BY: D Groves

Posted exercises for days 1, 2 and 3 in the series download folder.

Hello, Abrita, and thank you. M

Is it possible to access the NB files and quizzes for this class in the cloud?

Hello Michael,

While the notebooks are only available in the downloadable form right now, they will soon be available as part of the new interactive course on the Wolfram U site (as cloud notebooks). We just do not have a confirmed release date for that course yet.

The quizzes (with multiple choice questions) to be completed for Certificate of Program Completion will definitely be available on the cloud - same a other Daily Study Groups so far.

If you are referring to the programming exercises we added to the download folder, I think we can try to share cloud published versions of the exercises by the end of the week.

Please help me to fix this attempt to modify the p in addition to q and r:

Range[10]/.{p___,q_,r_} ->  { #^2&/@p, q r } 

(motivated by the 1st example from the 'Rule-Based Programming' section of the first class NB).

Also, transformation p-> 2*p leads to a strange result:

In[37]:= Range[10] /. {p___, q_, r_} -> {2 p, q r}      Out[37]= {**80640**, 90}

Thanks. M

PS What is wrong with using #^2&/@p where p corresponds to 8 initial elements of the list, given that "#^2&/@Range[8]" works as expected.

The following code should explain what parts of the expression Range[10] are matching p, q and r:

Range[10] /. {p___, q_, 
r_} -> {{"This is p: ", p}, {"This is q: ", q}, {"This is r: ", r}}

This is the output you get:

 {{"This is p: ", 1, 2, 3, 4, 5, 6, 7, 8}, {"This is q: ", 9}, {"This is r: ", 10}}

So what is essentially happening with the {#^2 & /@ p, q r} part of the expression is {#^2 & /@ 1, 2, 3, 4, 5, 6, 7, 8, q r} i.e. #^2 is mapped over the single element 1 and therefore gives the result {1, 2, 3, 4, 5, 6, 7, 8, 90}

This would give the expected result:

Range[10] /. {p___, q_, r_} :> Join[#^2 & /@ {p}, {q r}]

Awesome! Thank you very much, Abrita. Best. M

Range[10] /. {p___, q_, r_} :> {Hold[ 2 p], q r}

shows what's happening with 2 p. It is computing 2X2X3X4X5X6X7X8

p (from the RHS of the rule) is really a fragment of an expression. It needs to be explicitly turned into a list to get the output you are looking for. Maybe something like:

Range[10] /. {p___, q_, r_} :> Append[2 {p}, q r]

Abrita: "So what is essentially happening with the {#^2 & /@ p, q r} part of the expression is {#^2 & /@ 1, 2, 3, 4, 5, 6, 7, 8, q r} i.e. #^2 is mapped over the single element 1 and therefore gives the result {1, 2, 3, 4, 5, 6, 7, 8, 90} This would give the expected result: Range[10] /. {p__, q, r_} :> Join[#^2 & /@ {p}, {q r}]" **************************************************************************

Thanks! This opens a window to many opportunities such as this one: Range[10] /. {p__, q, r_} :> Flatten[{2 {p}, {q r}}]. Yet, I still have a question: what kind of object is p without {}? In other words, what is the sequence of "bare" comma-separated numbers from the WL perspective? I understand that in our case it is a "list" of arguments. But this is not a List. What is it?

Maybe you have already responded by saying that this is a fragment of an expression.. But there should be also some rules (default) telling M how to treat those... Could you please clarify?

For example, what is the rule leading to 2 p = 2X2X3X4X5X6X7X8? It even seems to contradict the treatment of p in the previous example where p was reduced to its first element (as you said, the "single element 1").

Thank you. M

Hi Michael,

p appears to be a Sequence.

I reached out to our instructor Dave Withoff for a more complete explanation, and here is the response from Dave:


"... start with an input like

In[]:= Range[10] /. {p___, q_, r_} -> p
Out[]= Sequence[1, 2, 3, 4, 5, 6, 7, 8]

to find out exactly what expression is matched to the named pattern "p" when the rule is applied. The result here shows that "p" will be replaced by Sequence[1, 2, 3, 4, 5, 6, 7, 8].

Inserting Sequence[1, 2, 3, 4, 5, 6, 7, 8] in place of p in 2 p, or equivalently, in Times[2, p], gives Times[2, Sequence[1, 2, 3, 4, 5, 6, 7, 8]]. The Sequence expression is spliced in to the enclosing expression in an early step of evaluation to get Times[2,1, 2, 3, 4, 5, 6, 7, 8], which subsequently evaluates to the observed result.

The handling of Sequence expressions will be explored in one of the last sessions of the study group series."


Hope this helps.

Dear Arbita and Dave. Your responses are very valuable, especially by teaching how to "huck" it (look under the hood). There is a lot to digest. Thank you. M

Michael—sequences can indeed be a little tricky, but they're a great tool to add to your arsenal. You can really start manipulating things at a low level once you have a grasp on them and how they work with patterns!

POSTED BY: Arben Kalziqi

Thank you, Arben, At first sight, it indeed seems so .... insignificant :(. I am sure that it is а misleading impression. This happens with everything really basic.

Hi Abrita!

The first chunk you posted:

Range[10] /. {p___, q_, r_} :> {Hold[ 2 p], q r}

...helped me find a solution to something related to what Richard Hewens posted. I found a different solution but I like yours so much better. THANK YOU! :-D

POSTED BY: Lori Johnson

Caesar Cipher example and Day 1 exercises have been added to the download folder.

Posted 2 years ago

Where is the link to the download folder?

POSTED BY: Syd Geraghty

Hi Syd, The link is included in the reminder emails you have been receiving from the Wolfram U Team. It is also shared during the session.

Hi Joel, You can join the Wolfram Community and participate in any discussion thread. This particular thread is dedicated to the Daily Study Group: A Guide to Programming and Mathematics with the Wolfram Language. You can click on "Follow this Post" to receive notifications of any activity on this thread. enter image description here

Dear Abrita. Due to the trip, my deadline was shifted till today. I submitted the solutions to three quizzes. In the last quiz, four problems were accepted, and one was rejected. I sent a file describing my solution to the rejected problem and asked to check if it was really wrong. It was sent to Wolfram-U, with attention to you and Arben. I do not worry about the final score but would like to understand the reason for rejection. Could you please help me with this? Thank you. Michael.

@Michael Partensky sometimes the auto-grader is unable to handle alternative solutions. All your solutions were accepted on manual grading.

Thank you. The auto-grader is an interesting creature on its own. Is it one of Wolfram's projects? If it is, please post a link. What are the grading criteria (in addition to the final result), the ideas behind it, how does it learn...? Are there wider applications, e.g., for a justice system, or for use by a Supernal being judging the Humans? Thanks again. Michael.

Posted 2 years ago

Do we have to post a reply to join the group?

POSTED BY: Joel Healy
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