Beginning Mathematica and Wolfram for Data Science Applications in Data Analysis Machine Learning and Neural Networks 2nd Edition Jalil Villalobos Alva - Download the full ebook now to never miss any detail
Beginning Mathematica and Wolfram for Data Science Applications in Data Analysis Machine Learning and Neural Networks 2nd Edition Jalil Villalobos Alva - Download the full ebook now to never miss any detail
https://ebookultra.com/download/data-mining-practical-machine-
learning-tools-and-techniques-2nd-edition-ian-h-witten/
Feature Engineering for Machine Learning Principles and
Techniques for Data Scientists 1st Edition Alice Zheng
https://ebookultra.com/download/feature-engineering-for-machine-
learning-principles-and-techniques-for-data-scientists-1st-edition-
alice-zheng/
https://ebookultra.com/download/microarray-data-analysis-methods-and-
applications-2nd-edition-pietro-hiram-guzzi/
https://ebookultra.com/download/data-analysis-and-applications-2-1st-
edition-edition-bozeman/
Beginning Mathematica and Wolfram for Data Science
Applications in Data Analysis Machine Learning and
Neural Networks 2nd Edition Jalil Villalobos Alva Digital
Instant Download
Author(s): Jalil Villalobos Alva
ISBN(s): 9798868803475, 886880347X
Edition: 2
File Details: PDF, 9.77 MB
Year: 2024
Language: english
Beginning Mathematica
and Wolfram for Data
Science
Applications in Data Analysis,
Machine Learning,
and Neural Networks
Second Edition
Introduction������������������������������������������������������������������������������������������������������������xix
v
Table of Contents
Improving Code��������������������������������������������������������������������������������������������������������������������������� 41
Code Performance����������������������������������������������������������������������������������������������������������������� 42
Handling Errors���������������������������������������������������������������������������������������������������������������������� 43
Debugging Techniques���������������������������������������������������������������������������������������������������������� 45
How Mathematica Works������������������������������������������������������������������������������������������������������������ 47
How Computations are Made (Form of Input)������������������������������������������������������������������������ 47
Searching for Assistance������������������������������������������������������������������������������������������������������� 50
Notebook Security����������������������������������������������������������������������������������������������������������������� 53
Summary������������������������������������������������������������������������������������������������������������������������������������ 54
vi
Table of Contents
vii
Table of Contents
Export���������������������������������������������������������������������������������������������������������������������������������������� 166
Other Formats���������������������������������������������������������������������������������������������������������������������� 169
XLS and XLSX Formats�������������������������������������������������������������������������������������������������������� 173
JSON Formats���������������������������������������������������������������������������������������������������������������������� 174
Content File Objects������������������������������������������������������������������������������������������������������������ 177
Searching Files with Wolfram Language����������������������������������������������������������������������������� 178
Connecting to External Services����������������������������������������������������������������������������������������������� 179
External Connections����������������������������������������������������������������������������������������������������������� 179
External Resources�������������������������������������������������������������������������������������������������������������� 181
Database and File Operations (SQL)������������������������������������������������������������������������������������ 184
Summary���������������������������������������������������������������������������������������������������������������������������������� 186
viii
Table of Contents
ix
Table of Contents
x
Table of Contents
xi
Table of Contents
Index��������������������������������������������������������������������������������������������������������������������� 451
xii
About the Author
Jalil Villalobos Alva is a Wolfram Language programmer and Mathematica user. He
graduated with a degree in engineering physics from the Universidad Iberoamericana
in Mexico City. His research background comprises quantum physics, bioinformatics,
proteomics, and protein design. His academic interests cover the topics of quantum
technology, bioinformatics, machine learning, artificial intelligence, stochastic
processes, and space engineering. During his idle hours, he likes playing soccer,
swimming, and listening to music.
xiii
About the Technical Reviewer
Andrew Yule is a co-founder and managing partner of
Pontem Analytics, a global consulting company in the
energy industry specializing in combining domain expertise
with data-driven solutions. Andrew has over 13 years of
professional experience leveraging the Wolfram Language
and was the recipient of the Wolfram Innovator Award in
2017. He is an editor for the Society of Petroleum Engineers,
The Way Ahead magazine, and is also currently a member
of the Young Entrepreneurial Council. His technical
background includes a bachelor’s degree in chemical
engineering from the Colorado School of Mines and a
master’s degree in data science from Southern Methodist
University.
xv
Acknowledgments
I want to thank the collective support and guidance received throughout the
development of this project’s second edition. The contributions of numerous past and
present individuals have played an integral role in shaping this work. Their assistance,
feedback, and mentorship have been invaluable, enriching the content and presentation
of this edition. I also want to thank the technical and staff reviewers for their valuable
comments and feedback during this manuscript. They both helped me improve the
material’s presentation and theoretical work. And finally, I would like to thank Las Des
Nestor and “Los Betos” for teaching me great mastery.
xvii
Introduction
Welcome to Beginning Mathematica and Wolfram for Data Science.
Why is data science important nowadays? Data science is an active topic that is
evolving daily; new methods, techniques, and data are created daily. Data science
is an interdisciplinary field involving scientific methods, algorithms, and systematic
procedures to extract data sets and thus better understand the data in its different
structures. It is a continuation of some theoretical data analysis fields such as statistics,
data mining, machine learning, and pattern analysis. With a unique objective, to extract
quantitative and qualitative information of value from the data being recollected from
various sources, and thus be able to objectively count an event for decision-making,
product development, pattern detection, or identification of new business areas.
xix
Introduction
• Artificial intelligence
• Machine learning
Even though many techniques exist, this list only shows a part of it since research on
data science, machine learning, and artificial neural networks is constantly increasing.
Prerequisites
This book is intended for readers who want to learn about Mathematica / Wolfram
Language and implement it in data science; it focuses on the basic principles of data
science as well as for programmers outside of software development, that is, people who
write code for their academic and research projects, including students, researchers,
teachers, and many others. The general audience is not expected to be familiar with
Wolfram Language or with the front-end program Mathematica, but little or any
experience is welcome. Previous knowledge of the syntax would be an advantage in
xx
Introduction
understanding how the commands work in Mathematica. If this is not the case, the
book provides the basic concepts of the Wolfram Language syntax. The fundamental
structure of expressions in the Wolfram Language. Basic handling and understanding of
Mathematica notebooks.
Prior knowledge or some experience with programming, mathematical concepts
such as numbers, trigonometric functions, and basic statistics are useful, along
with some understanding of mathematical modeling, which is also helpful but not
compulsory.
Wolfram Language is different from many other languages but very intuitive and
user-friendly to learn.
The book aims to teach the general structure of the Wolfram Language, data
structures, objects, and rules for writing efficient code, and at the same time, teach data
management techniques that allow them to solve problems in a simple and effective
way. Provide the reader with the basic tools of the Wolfram Language, such as creating
structured data, to support the construction of future practical projects.
For this new version, all the programming was carried out on a MacBook Air M1
with Sonoma 14 environment with the installation of version 13.3.1.0 and 14 of Wolfram
Mathematica. Wolfram Mathematica is currently supported in other environments such
as Linux, Windows, and macOS. The code found in the book works with both the Pro and
Student versions.
Book Conventions
Throughout the book, you may come across different words written distinctly from
others. Throughout the book, the words command, built-in functions, and functions may
be used as synonyms that mean Wolfram Language commands written in Mathematica.
So, a function will be written in the form of the real name; for example, RandomInteger.
The evaluation of expressions appears in the Mathematica In/Out format; the same
applies to blocks of code.
xxi
Introduction
The Layout
The book is written in a compact and focused way to cover the basic ideas behind the
Wolfram Language and cover details on more complex topics. Some chapters have been
revised and redesigned in this new version to focus on novice and advanced topics.
Chapter 1 discusses the starting topics of the Wolfram Language, basic syntax,
and basic concepts with some example application areas, followed by an overview of
the basic operations and debugging techniques, and concludes by discussing security
measures within a Mathematica session.
Chapter 2 provides the key concepts and commands for data manipulation,
sampling, types of objects, and some concepts of linear algebra—the introduction to
lists, an important concept to understand in the Wolfram Language.
Chapter 3 discusses how to work properly with data and the initiation of the core
structures for creating a dataset object, introducing concepts like associations and
association rules are discussed with a conclusion remarking how associations and
dataset constructions can be interpreted as a generalization of a hash table aiming to
expose a better understanding of internal structures inside the Wolfram Language,
including an overview of performing operations on a list and between lists and then
discussing various techniques applied to dataset objects.
Chapter 4 exposes the main ideas behind importing and exporting data with
examples throughout the chapter with common and newly added file formats. It also
presents a very powerful command known as SemanticImport, which can import data
elements that are natural language.
Chapter 5 covers the topic areas for new data visualization, common data plots, data
colors, data markers, and how to customize a plot. Basic commands for 2D plots and 3D
plots are presented, too.
Chapter 6 introduces the statistical data analysis. Starting with random data
generation begins by introducing some standard statistical measures, followed
by a discussion on creating statistical charts and performing an ordinary least
square method.
Chapter 7 exposes the basis for data exploration and reviews a central discussion on
the Wolfram Data Repository. Performing descriptive statistics and data visualization
inside Fisher’s Irises dataset objects is also covered.
xxii
Introduction
Chapter 8 starts with machine learning concepts and techniques, such as gradient
descent, linear regression, logistic regression, and cluster analysis, including examples
from various datasets like the Boston and Titanic datasets and newly implemented
features.
Chapter 9 introduces the key ideas and the basic theory to understand the
construction of neural networks in the Wolfram Language, such as layers, containers,
and graphs. The MXNet framework in the Wolfram Language scheme is also discussed.
Chapter 10 concludes the book by discussing training neural networks in the
Wolfram Language. In addition, the Wolfram Neural Net Repository is discussed with
an example application, examining how to access data inside Mathematica and the
retrieval of information, such as credit risk modeling fraud detection, and concluding
with the example of the LeNet neural network, reviewing the idea behind this neural
network and exposing the main points on the architecture with the help of the MXNet
graph operations and a final road map on the creation, evaluation, and deployment of
predictive models with the Wolfram Language. In this new version, LLM (large language
model) features are introduced with the connection to GPT services, use of chat cells,
and presentation of the GPT-1 and GPT-2 models.
xxiii
CHAPTER 1
Introduction
to Mathematica
The chapter begins with a preliminary introduction to why Mathematica is a useful and
practical tool. It explores the core concepts of the Wolfram Language and its syntax.
It starts by explaining the internal structure of Mathematica and how to add code
effectively. The concept of a notebook is introduced, which is important to understand
the type of format that Mathematica handles. The chapter examines this interface class
and demonstrates how notebooks simultaneously support code and text. In this way,
a notebook is a computable text file. Next, you inspect various add-ons that can be
employed within a notebook to help the user maximize their code’s capabilities.
The next section demonstrates how to write expressions in Mathematica, examining
topics such as arithmetic, algebra, symbols, global and local variables, built-in functions,
date and time formats, plotting functions, logical operators, performance measures,
delayed expressions, and accessing Wolfram Alpha. You then look at how Mathematica
performs code computations, including its accepted varieties of inputs and the
evaluation of these inputs. This chapter concludes with tips for seeking support within
Mathematica, managing and handling errors, searching for solutions, and safely dealing
with security concerns in notebooks that incorporate dynamic content.
Why Mathematica?
Mathematica is a mathematical software package created by Stephen Wolfram more
than 35 years ago. Its first official version (Mathematica 1.0) emerged in 1988 and
was created as an algebraic computational system capable of handling symbolic
computations. However, Mathematica has established itself as a tool capable of
performing complex tasks efficiently, automatically, and intuitively. Mathematica is
1
© Jalil Villalobos Alva 2024
J. Villalobos Alva, Beginning Mathematica and Wolfram for Data Science,
https://doi.org/10.1007/979-8-8688-0348-2_1
Chapter 1 Introduction to Mathematica
widely used in many disciplines like engineering, optics, physics, graph theory, financial
engineering, game development, and software development.
Mathematica provides a complete, integrated platform to import, analyze, and
visualize data. Mathematica does not require plug-ins. It also has a mixed syntax,
performing both symbolic and numerical calculations. It provides an accessible way
to read the code with the implementation of notebooks as a standard format, which
also serves to create detailed reports of the processes carried out. Mathematica can
be characterized as a powerful platform enabling efficient and concise forms of work.
Among computer languages, the Wolfram Language falls into the group of programming
languages classified as a high-level, multi-paradigm interpreted language. Unlike
conventional programming languages, the Wolfram Language adheres to unique rules,
facilitating order and clear, compact code composition.
2
Chapter 1 Introduction to Mathematica
–– Mathematica uses curly braces {} (e.g., {a, b, c}) to represent lists, arrays,
matrixes, and other collections.
Structure of Mathematica
Before entering code, you need to get the layout of Mathematica. To launch
Mathematica, go to your Applications folder and select the Mathematica icon. This
action brings up the new welcome screen, illustrated in Figure 1-1.
Figure 1-1. The default welcome screen for Mathematica’s latest version
3
Chapter 1 Introduction to Mathematica
Tip The startup window offers valuable information for new and adept users,
including the Mathematica version, access to documentation, resources, and the
Wolfram community, among other things.
After the startup screen appears, you can create a new notebook by selecting the New
Document button, and a blank page should appear like the one shown in Figure 1-2.
New documents can also be created by selecting File ➤ New ➤ Notebook or with the
⌘+N (macOS) or Ctrl+N (Win) keyboard shortcut command.
The blank document that appears is called a notebook, and it’s the core interaction
between the user and Mathematica. Notebooks can be saved locally from the menu bar
by selecting File ➤ Save (or Save as). Initializing Mathematica always exhibits an untitled
notebook. Notebooks serve as the standard document format. They can be customized
to display text alongside computations. However, the key feature of Mathematica lies
in its capacity to perform computations, extending beyond numerical calculations,
regardless of the notebook’s purpose.
4
Chapter 1 Introduction to Mathematica
Mathematica’s notebooks are separated into input spaces called cells. Cells are
represented by the square brackets on the notebook’s right side. Each input and output
cell has its bracket. Brackets enclosed by larger brackets are related computations,
whether input or output. Grouped cells are represented by nested brackets that contain
the whole evaluation cell. Other cells can be grouped by selecting and grouping them
with the right-click option. Cells can also have the capability to show or hide input by
simply double-clicking the cells. To add a new cell, move the text cursor down, and a flat
line should appear, marking the new cell ready to receive input expressions. The plus
tab in the line is the assistant input tab, showing the various types of input supported by
Mathematica. Figure 1-3 displays grouped input (In[-]) and output (Out[-]) cells.
There are four main input types. The default input is the Wolfram Language code
input. Free-form input is involved with Wolfram knowledge-base servers, and the results
are shown in Wolfram Language syntax. Wolfram Alpha query is associated with results
explicitly shown on the Wolfram Alpha website. External Language Input is built-in
support for common external programming supported by Mathematica.
There are four main input types.
• Default input: Wolfram Language code input
5
Chapter 1 Introduction to Mathematica
Tip Keyboard shortcuts for front-end instruction commands are shown on the
right or left side of each panel.
Design of Mathematica
Now that you have the lay of the land of Mathematica’s basic format, you can learn
the internal structure of how Mathematica works. Inside Mathematica, there are
two fundamental processes: the Mathematica kernel and the graphical interface.
The Mathematica kernel is the one that takes care of performing the programming
computations; it is where the Wolfram Language is interpreted and is associated with
each Mathematica session. The Mathematica interface allows the user to interact with the
Wolfram Language functions and, at the same time, document your progress.
6
Chapter 1 Introduction to Mathematica
Each notebook contains cells, where the commands that the Mathematica kernel
receives are written and then evaluated. Each cell has an associated number. There are
two types of cells: the Input cell and the Output cell. These are associated with each other
and have the following expressions: In[n]:= Expression and Out [n]: = Result or (“new
expr”). The evaluations are listed according to which cell is evaluated first and continue
in ascending order. When quitting the kernel session, all the information, computations
made, and stored variables are relinquished, and the kernel is restarted, including the
cell expressions. To quit a kernel session, select Evaluation ➤ Quit Kernel ➤ Local.
Tip To start a new kernel session, click Evaluation ➤ Start Kernel ➤ Local.
The computation shows that In and Out have a number enclosed. This number is the
number associated with the evaluated expression.
A suggestion bar appears after every expression is evaluated (see Figure 1-5).
The suggestion bar in Mathematica is always visible unless the user hides it. But the
suggestion bar offers suggestions for possible new commands or functions to be applied
to the generated output. The suggestion bar can sometimes be helpful if you are unsure
what to code next; if used wisely, it might be helpful.
7
Chapter 1 Introduction to Mathematica
8
Chapter 1 Introduction to Mathematica
Later, you learn about in-depth settings and customization options for the notebook
interface that allow you to tailor preferences.
Mathematica Environment
This section explores the user interface of Mathematica, with a focus on the notebook
interface, as well as the other user experience functionalities.
Notebook Interface
Mathematica is always on the quest to improve user experience and boost productivity.
In version 13.1, a big enhancement has been introduced—the seamless integration of a
default toolbar (see Figure 1-7) across all standard notebook user interfaces (UIs).
Figure 1-7. The new UI default toolbar showcases essential tools and
functionalities for efficient code development. Toolbar icons may vary by
Mathematica version
This new toolbar (described left to right) includes several new features to enhance
user experience. Evaluate allows users basic and costume code evaluation. Abort
lets users cancel queued cells and remove chosen ones; both options are shown
in Figure 1-8. These features can also be accessed via the keyboard, as previously
mentioned.
9
Chapter 1 Introduction to Mathematica
Figure 1-8. Extensive options for code evaluation and abort options in a notebook
interface; the double arrow-like shape hides the toolbar
The other options integrate text cell formatting, offering styling options like cell style
(title, subtitle, etc.) and cell color background. Users also benefit from the convenient
cell management functions, such as grouping, dividing, merging cells, and inserting
input/output of cells, all reduced to simple buttons. Continuing to options like extend
selection, convert natural language into Wolfram Language code, collapse cells, insert
comment, math form input, and LATEX rendering, users also have access to drawing
canvas and hyperlink features. Finally, the rightmost section of the toolbar includes
buttons for chat notebooks (utilizing LLM features), saving or publishing to the Wolfram
Cloud, accessing documentation (local or web-based), and searching within the
notebook.
Note Different buttons may appear based on the selected cell type where the
cursor resides, ranging from text to code formatting. Figure 1-7 shows for Wolfram
Language code input cell. Figure 1-9 shows for text display cell.
Figure 1-9. Text cell options for bold, italic, and underline and insert code text
evaluation and abort options in a notebook interface
10
Chapter 1 Introduction to Mathematica
This essential addition provides a coherent user experience and fosters a more
streamlined, productive programming environment within Mathematica. For example,
Figure 1-10 shows a code input cell with a colored background.
Figure 1-10. Light-green code input cell, with a 2pt black top margin
Besides the default toolbar, more improvements were made to the other toolbars,
Ruler, Formatting, Templating, and Testing, as Figure 1-11 shows. The last two are not
shown since they are more associated with a specific type of programmatic notebook,
which is beyond the scope of this book.
11
Chapter 1 Introduction to Mathematica
The prominent toolbar Ruler indicates and adjusts the text margins of specified cells
using draggable marks, offering control over the text format. The Formatting toolbar
brings advanced textual design options, while the Templating and Testing toolbars
(not shown in the image) facilitate the efficient creation of new templates and testing
programmatic notebooks.
Text Processing
Notebooks can include explanatory text, titles, sections, and subsections. The
Mathematica notebook resembles a computable document rather than a programming
command line. Text is useful for describing code and can be inserted into cells as text
cells, which often relate to the corresponding computations. Mathematica allows you to
work with multiple forms of text cells, including lines of text, chapters, formulas, items,
bullets, and more. Like a word-processing tool, notebooks can have titles, chapters,
sections, and subsections. By selecting Format ➤ Style, additional options become
available. For more control over style cells, use the formatting toolbar (see Figure 1-12)
found by navigating to Window ➤ Toolbar Formatting in the menu bar. The formatting
toolbar streamlines cell styling, allowing users to justify text left, center, right, or fully.
Figure 1-12. The Style Format toolbar has a user-friendly interface for
customizing text appearance
The cell types can be arranged in different forms, depending on the notebook’s
format. There are numerous forms to add text in a cell; the most straightforward is
to type the text in the input cell, and the Assistant tab input automatically suggests
converting it to text. Another alternative is to choose the cell type from the toolbars, with
the input chooser or the shortcut (⌘+7 or Ctrl+7).
Styled text can be created with the formatting toolbar or by selecting the desired style
in Format ➤ Style ➤ (title, chapter, text, code, input, etc.). In the Style menu, note the
keyboard shortcuts for all the available text styles. It can be used instead of going into
the menu bar every time. Plain text can also be converted into input text by formatting
the cell in the Input style. There is no restriction in converting text; text can be converted
into whatever style is supported in the format menu.
12
Chapter 1 Introduction to Mathematica
Note To convert text, highlight the text or select the cell that contains the text.
As shown in Figure 1-13, styled cells look different from others. Each style has
a unique order by which a notebook is organized into cell groups. A title cell has a
higher order in a notebook, so the other cells are anchored to the title cell, as shown
in Figure 1-13, but it does not mean that if another title cell is added, both titles are
grouped. If the title cell is collapsed, the title is the only displayed text.
Figure 1-13. A notebook with different format styles; this includes title, subtitle,
section, subsections, plain text, item list, and subitem list
Text can be given a particular style, changed, and different formats applied
throughout the notebook. By selecting Font or Show Fonts (macOS users) from the
Format menu, a pop-up window appears, allowing you to change the font, font style,
size, and other characteristics.
13
Chapter 1 Introduction to Mathematica
Tip To clear the format style of a cell, select the cell and then the right-click
button and choose Clear Formatting.
Palettes
Palettes show different ways to enter various commands into Mathematica. A
diverse quantity of special characters and typesetting symbols are used in the
Wolfram Language, which can be typed within expressions to more closely resemble
mathematical text. The best way to access these symbols is by using the pallets built
into Mathematica. To select a simple pallet, go to Pallets ➤Basic Math Assistant. Each
pallet has different tabs that stand for different categories with distinct commands and a
variety of characters or placeholders that can be inserted using the pallets. To enter the
symbol, type ESC followed by the name of the symbol, then ESC again. Try typing (ESC a
ESC) to type the lowercase alpha Greek letter. Figure 1-14 shows the basic math assistant
pallet in Mathematica.
14
Chapter 1 Introduction to Mathematica
15
Chapter 1 Introduction to Mathematica
example generates a large amount of data, which can be suppressed, displayed, or even
stored in the notebook (see Figure 1-15).
In[2]:= Table[i^12,{i,1,10^4}]
Out[2]=
Figure 1-15 shows that the input code returns a responsive output. Users can expand,
show, iconize, or select to store the whole data expression. Additionally, the data can
be fully stored in the notebook, preserving the entire output for future manipulation
and consuming 0.7MB of memory. If you iconize large outputs, a summary of the data
structure, length, and size is displayed. See Figure 1-16.
Figure 1-16. List structure with 10,000 items and a byte count of 682,696
Another aspect that has been renewed is the preference settings. The whole settings
display has undergone notable refreshment in terms of customization options, as
illustrated in Figure 1-6. Specifically, regarding the notebook front end, by selecting
the Appearance tab (see Figure 1-17), users can tailor their choices to optimize their
notebook code style, resulting in a more personalized experience.
16
Chapter 1 Introduction to Mathematica
Figure 1-17 shows Appearance Settings window. The Syntax Coloring tab is related
to the visual representation of code elements (variables, errors, automatic coloring,
highlighting, etc.). The Debugger tab includes coloring options about debugger
highlights, breakpoints, and evaluation points. The Numbers tab offers multiple choices
based on formatting and configuration choices, a few mentions are digits control
numerical notation, among others. The Graphics tab allows you to choose the render of
2D and 3D graphics, from lowest to highest quality.
Note To change the colors of the code syntax options in the Appearance
windows. Select the variables checkbox and click the green square. A color wheel
pops up, allowing you to change the color. This process is the same for the three
code setting options. Also, as you can see, there are different tabs.
17
Chapter 1 Introduction to Mathematica
Expression in Mathematica
Basic arithmetic operations can be performed in Mathematica with a common,
intuitive form.
In[4]:= 1002 ∗ 10
Out[4]= 100000
In[5]:= 2 1
Out[5]= 2
The standard Mathematica format aims to deliver the value closest to its regular
form, so when dealing with decimal numbers or general math notation, Mathematica
always gives you the best precision (involving, in some circumstances, infinite
precision). However, it allows you to manipulate expressions numerically, to display
numeric values, you use the N function. To insert the square root, type [Ctrl + 2].
In[6]:= 1/2 + 2
Out[6]= 1/2 + 2
In[7]:= N[1/2+ 2 ]
Out[7]= 1.91421
You can manage the number precision of a numeric expression. In this case, you
establish 10 decimal places.
In[8]:= N[77/13,10]
Out[8]= 5.923076923
For a shortcut to work with the decimal point, just type a dot (.) anywhere in the
expression, and with this, you are telling Mathematica to calculate the value with
machine precision.
18
Chapter 1 Introduction to Mathematica
4. 2
In[9]:= +
2 13
Out[9]= 2.15385
Mathematica performs the sequence of operations from left to right, in line with the
written expression, while adhering to the standard order of mathematical operations. To
evaluate an expression without showing the result, you add a semicolon (;) after the end
of the first term. In the following example, the 11/7 is evaluated but not shown, and the
other term is displayed.
The last form of code is called a compound expression. Expressions can be written in
a single line of code, and with compound expressions, they are evaluated in the intended
sequence. If you write the semicolon in each expression, Mathematica does not return
the values, but they are evaluated.
There is no output, but all the expressions have been evaluated. Later, you use
compound expressions to understand the concept of delayed expressions. This basic
feature of the Wolfram Language makes it possible for expressions to be evaluated but
not displayed to save memory.
Assigning Values
In the Wolfram Language, each variable requires a unique identifier that distinguishes
it from the others. A variable in the Wolfram Language can be a union of more than one
letter and digits; it must also not coincide with protected words—reserved words that
refer to commands or built-in functions. Keep in mind that the Wolfram Language is
case-sensitive. User variables are advised to be lowercase to avoid confusion with built-
in symbols.
19
Chapter 1 Introduction to Mathematica
In[12]:= a=Pi
x=11
z+y
Out[12]= π
Out[13]= 11
Out[14]= y+z
In the previous example, Mathematica expresses each output with its cell, even
though the input cell is just one. That is because Mathematica gives each cell a unique
identifier. To access previous evaluations, the symbol (%) is used. Additionally,
Mathematica lets you retrieve previous values using the cell input/output information by
the % # command and the number of the cell or by explicitly writing the command with
In [# of cell] or Out [# of cell]. As demonstrated in the next example, Mathematica gives
the same value for each expression.
In[15]:=
%12
In[12]
Out[12]
Out[15]= π
Out[16]= π
Out[17]= π
To determine whether a word is reserved within the Wolfram Language, use the
Attributes command; this displays the attributes to the associated command. Attributes
are general aspects that define functions in the Wolfram Language. When the word
“Protected” appears in the attributes, it means that the word of the function is reserved.
The next example shows whether the word “Power” is reserved.
20
Chapter 1 Introduction to Mathematica
In[18]:= Attributes[Power]
Out[18]= {Listable,NumericFunction,OneIdentity,Protected}
As seen in the attributes, “Power” is a protected word. Importantly, most of the built-
in functions in Mathematica are listable—that is, the function is interleaved to the lists
that appear as arguments to the function.
Variables can be presented in a notebook in the following ways: (1) global variables,
or those that are defined and can be used throughout the notebook, like the ones in
the earlier examples; and (2) local variables, which are defined in only one block that
corresponds to what is known as a module, in which they are only defined within
a module. A module has the following form: Module [symbol1, symbol 2... body of
module].
Variables inside a module turn green by default; this is a handy feature for seeing the
code inside a module block. A local variable only exists inside the module, so if you try to
access them outside their module, the symbol is unassigned, as shown in the following
example.
In[20]:= {l,k,h}
Out[20]= {l,k,h}
Variables can be cleared with multiple commands, but the most suitable command
is the Clear[symbol], which removes assigned values from the specified variable or
variables. So, if you evaluate the variable after Clear, Mathematica treats it as a symbol,
and you can check it with the command Head; Head always gives you the head of the
expression, which is the type of object in the Wolfram Language.
In[21]:= Clear[a,x]
And if you check the head a, you see that “a” is a symbol.
In[22]:= Head[a]
Out[22]= Symbol
Symbols or variables assigned during a session remain in the memory unless they
are removed or the kernel session ends.
21
Chapter 1 Introduction to Mathematica
Built-in Functions
Built-in commands or functions are written in common English with the first letter
capitalized. Some functions have abbreviations, while others employ PascalCase
notation with two capital letters. Here, different examples of functions are presented.
Built-in functions and group expressions often require arguments, which are values that
the function needs to execute the correct operation. Functions may or may not accept
arguments; they are separated by commas.
In[23]:= RandomInteger[]
Out[23]= 0
In[25]:= Power[2,2]
Out[25]= 4
In[26]:= d=Power[2,2]
F=Sin[π] + Cos[π]
Out[26]= 4
Out[27]= -1
In[28]:= Clear[d,F]
22
Chapter 1 Introduction to Mathematica
options, use Option. In the next example, the RandomReal function creates a pseudo-
random real number between an established interval.
In[29]:= Options[RandomReal]
Out[29]= {WorkingPrecision → MachinePrecision}
RandomReal has only one option for specifying specific instructions within the
WorkingPrecision command. The default value for this option is MachinePrecision.
WorkingPrecision defines the number of digits of precision for internal computations,
while MachinePrecision is the symbol used to approximate real numbers, denoted by
$MachinePrecision. To see the value of MachinePrecision, type $MachinePrecision. The
next example observes the difference between using default values for an option and
employing custom values.
In[30]:= RandomReal[{0,1},WorkingPrecision->MachinePrecision]
RandomReal[{0,1},WorkingPrecision->30]
Out[30]= 0.19858
Out[31]= 0.451259323577871140781571594337
The first one returns a value with six digits after the decimal point, and the other
returns a value with 30 digits after the decimal point. However, some built-in functions,
such as Power, do not have any options associated with them.
In[32]:= Options[Power]
Out[32]= {}
In[33]:=DateObject[]
Out[33]=
23
Chapter 1 Introduction to Mathematica
Figure 1-18. The date of Wed 13 Sept 2023 and time zone
DateObjects with no arguments give the current date, as shown in Figure 1-19.
Natural language is supported in Mathematica—for instance, getting the date after Wed
13 Sept 2023.
In[34]:= Tomorrow
Out[34]=
The date format is entered as year, month, and day. It also supports string date
formats and different calendars, as the next code dates show.
In[35]:= DateString[DateObject[{2020,6,10}]]
Out[35]= Wed 10 Jun 2020
In[36]:= DateString[DateObject[Today,CalendarType->"Julian"]]
DateString[DateObject[Today,CalendarType->"Jewish"]]
Out[36]= Wed 31 Aug 2023
Out[37]= Yom Revi'i 27 Elul 5783
The command also supports options that are related to a time zone.
In[38]:= DateString[DateObject[{2010,3,4},TimeZone->"America/Belize"]]
Out[38]= Thu 4 Mar 2010
Your current location’s sunrise and sunset times can be calculated (support data is
downloaded).
In[39]:= DateString[Sunset[Here,Now]]
DateString[Sunrise[Here,Yesterday]]
24
Chapter 1 Introduction to Mathematica
To get the current time, use TimeObject with zero arguments (see Figure 1-20). It can
be entered in the format of 24h or 12h. To introduce the time, enter the hour, minute,
and second.
In[41]:= TimeObject[]
Out[41]=
Time zone conversion is supported; convert 5 p.m. from GMT-5 Cancun time to
Pacific Time Los Angeles. You can also use DatesString to use pure string objects.
In[42]:=
DateString[TimeZoneConvert[TimeObject[{17,0,0},TimeZone-> "America/
Cancun"],"America/Los_Angeles"]]
Out[42]= 15:00:00
Strings
Text can be useful when a description of the code is needed. Mathematica allows you to
input text into cells and create a text cell related to your computations. Mathematica has
different forms to work with text cells. Text cells can have lines of text, and depending on
the purpose of the text, you can work with different text formats, like creating chapters,
sections, or just general text. In contrast, to text cells, you can introduce comments to
expressions that need an explanation of their purpose or just a description. For that, you
simply write the comment within the symbols (* *). And the comments are shown with
different colors; comments also always remain as unevaluated expressions. Comments
can be single-line or multiline.
Mathematica can work with strings. To input a string, enclose the text in quotation
marks “text”; Mathematica knows that it is dealing with text. Characters can be whatever
you type or enter into the cells.
25
Another Random Scribd Document
with Unrelated Content
The Project Gutenberg eBook of Sten Sture
nuorempi ja Kristiina Gyllenstjerna I: Ruotsin
Valkyria
This ebook is for the use of anyone anywhere in the United States
and most other parts of the world at no cost and with almost no
restrictions whatsoever. You may copy it, give it away or re-use it
under the terms of the Project Gutenberg License included with this
ebook or online at www.gutenberg.org. If you are not located in the
United States, you will have to check the laws of the country where
you are located before using this eBook.
Language: Finnish
Kirj.
1. Luostarimuurien sisällä.
2. Naisenryöstö.
3. Vaaralliset kirjeet.
4. Suomalaiset.
5. Synnin palkka täytyy hänen armonsakin pitää hyvänään.
6. Synnin palkka, millaisena se lankeaa jalosukuiselle rouvalle.
7. Pilvet vetäytyvät kokoon.
1.
LUOSTARIMUURIEN SISÄLLÄ.
"Kyllä minun vain täytyy sanoa, että aina kun Ingeborgini tulee
sieltä, on hänellä niin paljon kerrottavaa siitä, mitä niillä siunatuilla
sisarilla on pöydässään, ja kun kerran on varaa, miksei laittaisi yhtä
mainiota itselleen."
"Hienoa tietysti?"
"Kaikkea muuta!"
"Mitä nyt?"
"Mitä heillä oli ruokana? kysyin minä, kun hän tuli kotiin. Hän
ärähti vihaisesti: Kärvennettyä lampaanlapaa ja hapankaljaa
saadakseni ei minun tarvitse mennä luostariin!"
"Ja sitten?"
"Kuinka niin?"
"Sillille ja leivälle?"
"Sitä en usko."
"Niin, en minäkään."
"Vaikken tahdo sanoa mitään."
"Mitä niin?"
"Kenen tähden?"
"Niinkuin muuri."
"Veli Mathias…"
"Lasimestari?"
"Niin!"
"Jollei häntä olisi ollut, emme kai olisi koskaan saaneet mitään
lasi-ikkunoita. Minun mieheni mielestä oli synti laittaa niin kovin
valoisaa, ja kun isillämmekin on ollut ainoastaan lyijyruutuja, niin
voimmehan mekin niihin tyytyä."
"Kysy Mathiaalta!"
"En, tietysti!… Mutta sanoa se juuri nyt, kun hän tahtoo tehdä
meille niin suuren palveluksen…"
"Minkä sitten?"
"Veli Laurentius!"
"Tervetuloa kotiin!"
"Kiitos, kiitos!"
"Sellaiset pakkaset!"
"Vaivalloiset tiet?"
"Miten milloinkin."
"Abbedissa?"
"Sinä rakastat?"
"Ketä?"
"Käsken sen!"
"Hänen nimensä?"
"Kaarina Eliaantytär."
"Juuri hän!"
"Mitä varten?"
"Hän uskaltaa?"
"Huomenna!"
"Millä tavoin?"
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebookultra.com