[WSG21] Daily Study Group: programming tutorials
|
|
A few more words about MC and Pi. Using the "weighting" or, equivalently, the " regular grid " approaches to determining the relative area of a circle (or the value of Pi) is not inferior to using MC with RNG. In both cases the error ~ N^(-1/2). MC is a nice Demo, but there is nothing really mind-boggling about it. Thanks for raising this questions. I had some suspicions before, but had never took time to think it through.
|
|
Good video! Interestingly, when we touched the "weighting" approach to Pi, and the "atomic precision", it was actually about the atomic plane, similar to a grid displayed in the video. You have to draw a circle in such a plane (How? :)) and them to decide which atoms are in and which are out...sort of. And, funny to say, the Planck constant will likely determine the corresponding precision of Pi. So, it seems to me that the discussion in video has a straight "atomic analogy"... In physics, this realm of questions was wonderfully outlined by Eugene Wigner (if you did not have a chance, please check it: https://www.maths.ed.ac.uk/~v1ranick/papers/wigner.pdf "THE UNREASONABLE EFFECTIVENSS OF MATHEMATICS IN THE NATURAL SCIENCES". )... Best regards.
|
|
Pi in terms of Gaussian numbers and the distribution of primes (it has the feel of Monte-Carlo without RGNs) :) https://tinyurl.com/p54hjtee
|
|
It seemed to me that Monte-Carlo itself relies on RNGs. It always starts with random moves. In physical applications they can be accepted or rejected based on their "energy cost". I guess, you meant a simplest and may be the most beautiful example of MC, - finding the value of Pi (by randomly shooting "rounds" at the target and counting fraction that entered the circle of a given R). But the accuracy of the obtained Pi will depend, among the other factors, on the quality of RNG (on how random the shots are). The Pi itself is obtained by regular mathematical means, not relying on randomness. Interestingly, there is also purely "physical" way of "measuring" the Pi.
Take a 1x1 square made of a uniform material, and measure its weight Wsq. Then, cut from it a circle of D=1. Find its weight. Wci. The rest is straightforward. The real challenge would be measuring Pi with "atomic" (quantum? ) precision. I know it sounds funny :)
|
|
So it seems that pi is not a good random number generator but the fact that you can generate pi using random number techniques (monte carlo method) still boggles my mind.
|
|
Here is the expected output for problem 2 with ListLinePlot3D:

|
|
OH, GOOD! I was wondering. Thanks, Abrita!
|
|
Hi, Abrita. Probably, I have missed the announcement. Are the NB files for the last Review session available? Thank you.
M
|
|
Did anybody get the NB files for the Review III session (August 20)?
|
|
Did anybody get the NB files for the Review III session (August 20)?
|
|
We plan to post the notebook from the final review session soon. Sorry for the delay.
|
|
[WSG21] Daily Study Group: programming tutorials
|
|
I agree that the output is cooler with ListLinePlot3D, but I didn't see how to make it match the expected Output.
|
|
Abrita has stated above that "Sorry about the expected output and auto grader solution not matching the exercise text. The exercise will be updated on Monday. Thank you for your patience" So, it seems we will have to wait till Monday to see if the new "output " looks like this, otherwise back to the drawing board. 
It took a while to work out ListLinePlot3D is new in 12.3 so does not work in my 12.2 version [1
|
|
I could certainly be wrong, but... In the exercises, #2, I don't think you meant ListLinePlot3D. I got the correct answer (per auto-grader) using another function.
Ron
|
|
We do want you to use ListLinePlot3D. The output will look way cooler :) Sorry about the expected output and auto grader solution not matching the exercise text. The exercise will be updated on Monday. Thank you for your patience.
|
|
There seem to be two possibilities: either the expected result (the picture) was correct while the proposed function was wrong, or vice versa. In any case, trying to solve under both assumptions was good for learning. The closest I could get under the first scenario (trying to reproduce the original plot using ListLinePLot3D) was by setting "Joined -> False" in ListLinePlot3D , which turned lines into points. In my humble opinion, the original ( with the dots) picture is clear and instructive, while the second is beautiful, impressionistic and hardly interpretable. In combination with the story, it can make a nice NFT. Any way, thank you for the wonderful brain teaser. The errors like this must be included by design!
PS. By the way, while playing with the functions, try using the "plane" version ListLinePlot [list, ColorFunction -> "Rainbow"]
(both with "Filling->Bottom", shown below, and without it *), Aren't they nice?! "? :) 
|
|
Deadlines for Quiz and Exercise submissions:
- Quizzes (for Certificate of Program Completion): Aug 27, 2021
- Programming Exercises (for Level 1 Certification for Proficiency in Using the Wolfram Language): Sep 3, 2021
|
|
There were several unsatisfactory answers (IMO) given in yesterday's session. I had asked if resetting \
$`Line` erased the history entries, or if they persisted until a new entry was evaluated with the `In[]` number. The instructor didn't really answer the question at all (perhaps he didn't understand what I was asking) and simply reiterated that setting \$Line caused the In[] numbers to start again from that value. In a similar vein, someone had asked (I think) about measuring the amount of memory tied up in history entries and did not get a relevant answer. In any case, for those who may be interested, experimentation shows that changing \$Line does not immediately erase any history entries. And I think an estimate of the amount of space used by previous results can be obtained by
Total[ByteCount /@ Out[Range[$Line - 1]]]
(Out[ \$Line] itself has to be excluded to avoid recursion.) But I couldn't figure out how to find the space occupied by the In[] entries, given that I don't actually want to reevaluate them. Which leads me to mention the third poor or missing reply yesterday. Someone suggested that the correct answer to Poll question 2 "How would you evaluate a previous input?" was not in fact "d. All of the above", as answers b. and c. merely retrieve a previous result, rather than reevaluating the expression that produced it. I agree completely. As stated, the answer should be "a. In[-k] for the input k lines back". Of course In[n] for the specific line n also works, as does re-evaluating the cell in question as suggested in answer e.
|
|
Sorry about the unsatisfactory answers. Your conclusion is correct.
"\$Line" is just a global variable that specifies the number of the current input line. It can be reset without erasing the input history. However as you start evaluating inputs with the new line number, new lines are numbered so as to overwrite previous ones with the same numbers. There is however "\$HistoryLength" to specify the number of previous lines of input and output to keep in a Wolfram System session. So by resetting it you can reduce memory usage in a session by limiting the amount of history that is remembered. At any point MemoryInUse gives the number of bytes currently being used to store all data in the current Wolfram Language kernel session. Here are some functions that provide information about the Wolfram System Session https://reference.wolfram.com/language/guide/WolframSystemSessionInformation.html but we do not have one that specifically gives the memory used just by the previous input lines. As for the poll question, we could perhaps rephrase it to "Which of the following can be used to re-evaluate a previous input?"
|
|
Issue with WorkBench installation ; For some reason, Eclipse does not show the "Wolfram Workbench webMathematica". I only see the "Wolfram WorkBench core". Tried to add a path to my local Mathematica, but Eclipse does not accept it.
Please, advise.
|
|
On the issue with webMathematica on Workbench install, I remember seeing both Wolfram Core and Wolfram webMathematica being on the list of options but only Core was checked by default on my system.
|
|
Michael, we have requested Support to get back to you on this over email.
|
|
Pursuant to my question during today's session about why Remove[Global`square] and Remove[Global`fun1] were said to be necessary, I experimented with leaving it out. I tried the following extracts from the lesson notebook, starting with a fresh kernel:
In[1]:= Begin["mathOperations`"];
square[x_] := x^2
End[];
In[4]:= $Context (* current context *)
square[10] (* returns unevaluated since the current context is not mathOperations` *)
mathOperations`square[10]
Out[4]:= Global`
Out[5]:= square[10]
Out[6]:= mathOperations`square[10]
In[7]:= PrependTo[$ContextPath, "mathOperations`"];
In[8]:= square[10]
Out[8]:= 100
Although a Global`square did indeed exist, presumably created by the reference to the undefined square by In[5]:
In[9]:= Names["Global`*"]
Out[9]:= {Global`square}
But as observed, the short name square still refers to the function we created, presumably because mathOperations occurs in $ContextPath before `Globals` . Hence the Remove[] call in the original notebook was just an act of excess caution.
Does this seem right?
|
|
A reply from Jayanta Phadikar (original author of the Programming Tutorials): It is correct that if context 1 precedes context 2 in $ContextPath, the system will use the context 1 definition. Here is an experiment:
In[7]:= Begin["context1`"];
func[] := "From Context 1";
End[];
Begin["context2`"];
func[] := "From Context 2";
End[];
In[26]:= $ContextPath = Flatten[Prepend[$ContextPath, {"context1`", "context2`"}]];
func[]
Out[27]= "From Context 1"
In[28]:= $ContextPath = Flatten[Prepend[$ContextPath, {"context2`", "context1`"}]];
func[]
Out[29]= "From Context 2"
In practice we should however avoid keeping symbols that are common in two different contexts (it is fine of course to keep common symbols in Private contexts). Since without checking the order in $ContextPath we won't know which definition is being used. The red syntax coloring is exactly meant for this warning. So the Remove expression was meant for ensuring that there is no duplication. Side note: it is correct that the square symbol in the Global context was created by In[7] .
|
|
This is about the question 8 of the Test 2:
Which attribute of Plot causes it to return an error when the following expression is evaluated?
Plot[Integrate[x,x],{x,-10,10}]:
(a) HoldRest, (b) HoldFirst, (c) HoldAll, (d) Hold Pattern To avoid the error, the function Integrate[x,x] can be evaluated to 0.5 x^2 before x is allowed to vary.
This can be done, e.g., by switching to Plot[Evaluate[Integrate[x,x]], {x,-10,10}]. However, the question suggests to focus on the (alleged) attribute(s) of the Plot. Attributes[Plot] does not include any of the suggested choices (a)-(d). I would appreciate any possible hints that won't compromise the integrity of the Test.
|
|
Try evaluating an expression using Plot , then check the Attributes . Take a look at this post on MSE for details.
|
|
I am working on a Wolfram Challenge to determine whether or not a geographic point's antipode is above sea level or not (https://challenges.wolfram.com/challenge/antipode-above-or-below-sea-level). I have some code that I am attaching in a notebook in case anyone happens to be working on Wolfram Challenges and does not want to view the solution. The test coordinates should return True and are for Beijing China. The problem is I keep getting a Network Time Out error.
How can I resolve this?
I tried to use EntityPrefetch but that did not fix the problem. I hope Internet speed is not the problem.
|
|
Hi Peter A location within
EntityValue[Entity["GeographicRegion", "World"], "Polygon"]
can be below sea level. e.g. Death Valley, Dead Sea, ... An alternative approach is in the attached notebook - to avoid spoiler.
|
|
That's genius!
I figured out a way to help with the issue of the network timing out.
|
|
Quiz 1, Problem 8. None of the answers seem to be correct. Am I missing something?
|
|
This would work after reformatting the input to "too bee or not". However, my grade is 90, and this frivolity seems to be the only plausible reason for its reduction.
|
|
In an earlier version of the quiz, the quotes were missing around ""too bee or not". The correctly formatted expressions should be:
StringCases["too bee or not", x_ ~~ x_]
StringCases["too bee or not", ("o" | "e") ..]
StringReplace["too bee or not", x_ ~~ x_ :> StringJoin[x, x]]
StringCases["too bee or not", ("o" || "e") ..]
|
|
Great point. And the example is really telling. Thank you!
M
|
|
Is there a relation between the attributes of a user-built function f (if none of attributes have been assigned to it), to the attributes of built-in functions included in f?
And specifically, why Attributes[f3] returns {} if it does exactly what the Sum does?
f3[x_, y_] := Sum[x, y];
Attributes[f3] ={}..
Probably, the answer should be obvious: when M evaluates Sum, it deals with the attributes of Sum. But this still may trigger some extra question (say, about a possible conflicts between attributes assigned to f3, and the existing attributes of built in functions). Hence, I would appreciate your take on this issue. Thank you. M
|
|
Attributes[f3] returns an empty list {} because f3 itself has no attributes permanently set for it. If within the definition of f3, there are calls to some built-in functions, the attributes of the built-in functions will work independently on the inputs being provided to the built-in function itself, regardless of the original inputs to the user-defined function. Within the function definition everything will get evaluated according to the "Standard Evaluation Procedure" which will take into account the attributes of the built-in function. (This tutorial on "Evaluation of Expressions" may explain some of the process, and the concept of assigning attributes, a little more https://reference.wolfram.com/language/tutorial/EvaluationOfExpressions.html).
|
|
Hi Peter, Perhaps I am not understanding what you are trying to do. What is wrong with
squared = Function[x, x^2] (* or squared = #^2& *)
squared[5]
(* 25 *)
ClearAll[squared];
pureToNamed[named_, pure_] := named = pure
pureToNamed[squared, Function[x, x^2]]
squared[5]
(* 25 *)
Your example works fine too
SetDelayed[seventhpower,Function[x,x^7]]
seventhpower[2]
(* 128 *)
|
|
Hi Peter,
wolfieSay = ResourceFunction["WolfieSay"];
wolfieSay["Hello"]

resourceFunctionToSymbol[rfName_String, symbolName_String] := (ClearAll@symbolName;
Evaluate@Symbol[symbolName] = ResourceFunction[rfName];)
resourceFunctionToSymbol["Alphametic", "myAlphametic"]
myAlphametic["SEND+MORE=MONEY"]
(* {{{"D" -> "7", "E" -> "5", "M" -> "1", "N" -> "6", "O" -> "0",
"R" -> "8", "S" -> "9", "Y" -> "2"}, "9567+1085=10652"}} *)
|
|
Thank you! This is a great help.
|
|
Is there a way to define the function globally in my system so that when I close Mathematica and open a new document the function is still defined. I realized that the function only works within a session.
|
|
You can add the definition(s) to $UserBaseDirectory/Kernel/init.m .
|
|
I am working with pure function and am wondering if there is a way to make a named function out of a pure function. For example is there a way to take the pure anonymous lambda function Function[x,x^2] and SetDelayed to create Square[x_]=x^2. I am working on creating a function that takes in a function name and a pure function and creates a function out of it. This is my goal
PuretoNamedFunction(sample name)[functionname_,purefunction_]:=
"solution here"
. I tried SetDelayed[seventhpower,Function[x,x^7]]. I also tried using Block and With.
|
|
The yellow box with the italic print is just one way of representing entity properties.
Entity properties are also represented as plain strings within quotes. These string names for the properties are accessible from the auto-completion menu that comes up when you type in [" immediately following the entity. For example:
 You can also get to the entire Wolfram Language interpretation of both Entity and the EntityProperty by typing in a natural language query after the = sign in an input cell:
 and then hit enter to see the following:
 An EntityProperty is always associated with an Entity. So if you are interested in a property, look at the documentation for the Entity you think it will be associated with. If I am interested in a property like "Literacy Rate", it would be a property I would associate with an Entity like a "country". So I could look within the "Properties" section at https://reference.wolfram.com/language/ref/entity/Country.html Similarly "Elevation" sounds like a property associated with a mountain. So I could look for it at http://reference.wolfram.com/language/ref/entity/Mountain.html or type in :
 Hope this helps.
|
|
I get that, thanks. I'm just wondering if there's a shortcut for writing the italic-yellow-box form of an attribute. Because yes, if you type "area of New York City" in a natural language entry box you can get , but much of the time, notebooks don't include it in that form. For example, this week's quiz has: 
And yesterday's example notebook has: 
So, is it the case that all these notebook authors created those cells by typing "area of New York City" then completely reformatting the expressions using copy/paste… or is there a way to type a property directly?
|
|
I believe the author wrote out:
EntityProperty["City", "Area"]
and evaluated using Shift+Enter to get the output in a separate cell (to copy and paste) or selected the code snippet and evaluated in place from the menu Evaluation -> Evaluate in Place or shortcut keys Shift+Ctrl+Enter (Windows) or Cmd+Return (Macintosh). If you hover over a formatted EntityProperty, it will show you the InputForm that you could write out in full, in the tootip.
|
|
Thank you, that helps a lot! Have a good one.
|
|
How can I type the yellow-box form of a property? They appear italic in the example notebook, like "electric charge". When I press ctrl+= and type elevation for example, I sometimes get a gray box that when confirmed turns into a string "Elevation" . Sometimes I get "No Wolfram Language translation found." Never do I get a property that looks like what's in the example notebook. An instructor answered that if you type EntityProperty["River", "Length"] , then the property is printed in italic-yellow-box form like in the example notebook. Does that mean that the example notebook was written by evaluating EntityProperty and copy/pasting? What about "fertilizer production" which was used in the last example today, for which I don't know the entity class it applies to?
|
|
I am registered in the course, but I am not getting the messages with the links to be able to attend the sessions.
|
|
- What is the total number of posted recordings? In my email I found just 5. Is it all? Please post the link to recordings.
- Could you please post a link to the most recent updates of the notebook files.
Thank you. M
|
|
You can view the recordings on the series signup page here. The link to the notebooks will be included in the reminder email.
|
|
I was am interested in converting various quantities such as the mass of the observable Universe, the number of particles in the observable Universe, the age of Universe, the speed of light, the surface area of the Universe as a ball and its cross-section, the width and volume of the Universe to Planck units. I am wondering if there is a way to specify with UnitConvert to convert to Planck length, time, and mass. I have read the documentation on UnitConvert and am wondering if there is a way to go about my project. The following code returns an error:
UnitConvert[{Quantity[1, "SpeedOfLight"],Quantity[1, "UniverseMass"]},
TargetUnits -> {Quantity[1, "PlanckLength"],
Quantity[1, "PlanckMass"], Quantity[1, "PlanckTime"]}]
I was wondering if there is a way to specify PlanckUnits as the UnitSystem or define my own unit system. I found an example that relates to NonDimensionalTransform documentation.

|
|
UnitConvert would work as follows:
In[19]:= UnitConvert[Quantity[1, "SpeedOfLight"], "PlanckLength/second"]
Out[19]= Quantity[1.8549*10^43, ("PlanckLength")/("Seconds")]
In[18]:= UnitConvert[Quantity[1, "UniverseMass"], "PlanckMass"]
Out[18]= Quantity[7.*10^60, "PlanckMass"]
TargetUnits is an option available for use with visualization functions e.g. ListPlot
Symbolic computations can definitely be performed with Quantity expressions as described here: http://reference.wolfram.com/language/tutorial/SymbolicCalculationsWithUnits.html
|
|
I am working on mapping the nearest nuclear reactor and first aim to select nuclear reactors that are in the United States.
I have the following code:
Select[EntityList[EntityClass["NuclearReactor", All]],
EntityValue[#, "Countries"] == Entity["Country", "UnitedStates"] &] but receive an empty list as a result for some reason.
How can I select all nuclear reactors in the US?
I would like to use the Select function.
|
|
The reason you get an empty list is because the == condition is failing. EntityValue[#,"Countries"] comes back as a list and so you never find a match for the list against the single entity of Entity["Country", "UnitedStates"] Try instead:
Select[EntityList[EntityClass["NuclearReactor", All]],
MemberQ[EntityValue[#, "Countries"],
Entity["Country", "UnitedStates"]] &]
or
EntityList[
FilteredEntityClass["NuclearReactor",
EntityFunction[c,
MemberQ[c["Countries"], Entity["Country", "UnitedStates"]]]]]
|
|
How do choose not as a condition with patterns?
For example,
mylist={1,1.5,2,3,3.14,2.718}
list /. _! Integer :> "Real"
I was also wondering how to replace all integers with "Int" and all reals with "Real" in one line.
I think there is a way to use replace with lists
mylist /. {_Integer, _Real} :> {"Integer", "Real"}
The previous code does not work.
How would I use conditions and patterns to replace each element of string list equal to False with Style[False, Red] and each element of string list equal to True with Style[True, Green]?
stringlist={True,False,False,True,False,False,True,False,True,True,False}
Example Notebook->
|
|
Re-read your last question. I think this is what you were looking for
Style[#, If[#, Green, Red]] & /@ stringlist

|
|
I didn't see a recording for Day 2. Is there one?
|
|
I am in the Programming Study Group. I have a practical problem I am trying to solve. I am trying to make a network graph on a hexagonal/triangular grid. All of the edges are directional and I need to have each edge represented by a symmetrical trapezoid where the edge thickness is narrower at the originating point than at the destination point on the grid. I was hoping EdgeShapeFunction would allow me to do this, but while GraphElementData knows about trapezoids, Wolfram Language doesn't seem to want to let me use a trapezoid as an EdgeShapeFunction. Is there another way to accomplish this?
|
|
Here is something to get you started:
Graph[{1 -> 2, 2 -> 3, 3 -> 1},
EdgeShapeFunction ->
Function[{coord, edge},
Tooltip[
Triangle[{First[coord], Last[coord] + {0, 0.04},
Last[coord] - {0, 0.04}}], {First@coord, Last@coord}]]]
The EdgeShapeFunction needs to be set to a pure function that will take the coordinates of the edge line and create something closer to your requirements. In the above example I created a triangle.
The Tooltip is only intended to show what the inputs to the pure function look like when it tries to draw the edge.
|
|
Very cool trick. I had no idea we had that much control over the appearance of a graph.
|
|
Part of the answer to my question is that the trapezoid elements in GraphElementData are set up for use with vertices as shown here:
Table[EdgeTaggedGraph[{1 \[UndirectedEdge] 2, 2 \[UndirectedEdge] 3,
3 \[UndirectedEdge] 1}, VertexShapeFunction -> s,
VertexSize -> 0.2, PlotLabel -> Style[s, 9]], {s,
GraphElementData["VertexShapeFunction", "Rounded"]}]
https://wolfram.com/xid/0cpsizfbsjq8gq-lsz53w
|
|
Can I have the link to the "Series 15 Programming Tutorials" webpage containing the exercises etc
|
|
The weekly quizzes will be announced on Fridays, and the exercises will be announced during the final week of the Study Group. Watch your email notifications for direct links to recordings, the quizzes and exercises, and additional resources.
|
|
What is the Level I Certification in, exactly? Is it different from the Wolfram Technology Level I Certification?
|
|
Here is the series landing page, where you can see details and from where all session recordings will be linked: https://www.bigmarker.com/series/daily-study-group-programming-tutorials/series_details The weekly quizzes will be announced on Fridays, and the exercises will be announced during the final week of the Study Group. Watch your email notifications for direct links to recordings, the quizzes and exercises, and additional resources.
|
|
Sorry, I did not find the links to recording in the aforementioned page.
What is the total number of posted recordings? In my email I found just 5. Is it all?
Thank you.
M
|
|
For this Study Group, the certification refers to Wolfram Technology Certified Level 1 for proficiency in using the Wolfram Language. This Level 1 certification is equivalent to the one you can earn by taking the Wolfram Language Level 1 exam on the Wolfram U website.
|
|
The .nb files are Wolfram Notebooks. You can open and work with the notebooks with a free trial.
|
|
I have never participated in a webinar like this. The study materials .nb downloads. Don't look familiar or readable. What am I supposed to do with them?
|
|
Download files again , this has been corrected .
|
|
Right! Sorry for the error.
|
|
Reply to this discussion
in reply to
|