Skip to content

Commit fc3744d

Browse files
committed
Replaced Java NewtonRaphson with Scala.
1 parent 80445b0 commit fc3744d

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
//> using scala 3.4.2
2+
3+
@main def run(x0: Double, eps: Double) = println(NewtonRaphson.solve(x0, eps))
4+
5+
object NewtonRaphson:
6+
def f(x: Double) = math.exp(-x) - math.sin(x)
7+
8+
def fprim(x: Double) = -math.exp(-x) - math.cos(x)
9+
10+
def solve(start: Double, eps: Double) =
11+
var x0 = start
12+
var x1 = start
13+
while {
14+
x0 = x1
15+
x1 = x0 - f(x0) / fprim(x0)
16+
math.abs(x1 - x0) > math.abs(x1) * eps
17+
} do ()
18+
x1

lab-instructions/modules/latex/example/latexlosning.tex

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@
1818
\usepackage{graphicx}
1919

2020

21-
2221
\title{Newton-Raphsons metod}
2322
\author{Per Holm}
2423
\date{21 maj 2001} % OBS! Vet inte när Per skrev dokumentet, jag hittade på ett datum.
@@ -121,7 +120,8 @@ \subsection{Konvergens}
121120

122121

123122

124-
\section{Newton-Raphsons metod i Java}
123+
% \section{Newton-Raphsons metod i Java}
124+
\section{Newton-Raphsons metod i Scala}
125125

126126
Det är inte helt enkelt att implementera Newton-Raphsons metod i ett
127127
program, åtminstone inte om man kräver att metoden ska fungera i
@@ -130,6 +130,7 @@ \section{Newton-Raphsons metod i Java}
130130
undantagsfall som finns eller fel som kan inträffa, till exempel
131131
att derivatan \texttt{fprim(x0)} blir nära noll (se avsnitt~\ref{sec:konv}).
132132

133-
\VerbatimInput{NewtonRaphson.java}
133+
% \VerbatimInput{NewtonRaphson.java}
134+
\VerbatimInput{NewtonRaphson.scala}
134135

135136
\end{document} % Slut på dokumentet

0 commit comments

Comments
 (0)