library(mosaicCalc)
## Loading required package: mosaic
## Registered S3 method overwritten by 'mosaic':
## method from
## fortify.SpatialPolygonsDataFrame ggplot2
##
## The 'mosaic' package masks several functions from core packages in order to add
## additional features. The original behavior of these functions should not be affected by this.
##
## Attaching package: 'mosaic'
## The following objects are masked from 'package:dplyr':
##
## count, do, tally
## The following object is masked from 'package:Matrix':
##
## mean
## The following object is masked from 'package:ggplot2':
##
## stat
## The following objects are masked from 'package:stats':
##
## binom.test, cor, cor.test, cov, fivenum, IQR, median, prop.test,
## quantile, sd, t.test, var
## The following objects are masked from 'package:base':
##
## max, mean, min, prod, range, sample, sum
## Loading required package: mosaicCore
##
## Attaching package: 'mosaicCore'
## The following objects are masked from 'package:dplyr':
##
## count, tally
## The legacy packages maptools, rgdal, and rgeos, underpinning the sp package,
## which was just loaded, were retired in October 2023.
## Please refer to R-spatial evolution reports for details, especially
## https://r-spatial.org/r/2023/05/15/evolution4.html.
## It may be desirable to make the sf package available;
## package maintainers should consider adding sf to Suggests:.
##
## Attaching package: 'mosaicCalc'
## The following object is masked from 'package:stats':
##
## D
Membuat fungsi golden section search
golden <- function (f, a, b, tol=0.0000001){
ratio <- 2 / ( sqrt (5)+1)
x1 <- b-ratio * (b-a)
x2 <- a+ratio * (b-a)
f1 <- f(x1)
f2 <- f(x2)
while ( abs (b-a)>tol){
if (f2>f1){
b <- x2
x2 <- x1
f2 <- f1
x1 <- b-ratio * (b-a)
f1 <- f(x1)} else {
a <- x1
x1 <- x2
f1 <- f2
x2 <- a+ratio * (b-a)
f2 <- f(x2)
}
}
return ((a+b) / 2)
}
# Membuat fungsi f(x)
f <- function(x) {abs(x-3.5)+(x-2)^2}
# Membuat plot
curve(f, 1,5)
# Menghitung nilai optimum
golden(f,1,2)
## [1] 2
golden(f,1,5)
## [1] 2.5
golden(f,3,5)
## [1] 3
Jika dilihat secara plot grafik, maka terlihat nilai minimum ada di antara nilai x= 2 dan x = 3. Dengan menggunakan fungsi golden section search dengan interval 1 <x<5 terlihat bahwa nilai minimum berada di x = 2.5.
f <- function(x) {(2 * sin(x)) - ((x^2) /10)}
fa <- function(x) -1 * f(x) # fungsi dikali dengan -1 karena fungsi yang dibuat meminimumkan
# Membuat plot
curve(f, 0,4)
# Menghitung nilai optimum
golden(fa,0,4)
## [1] 1.427552
Jika dilihat dari plot tersebut, pada interval 0 < x < 4 nilai optimum terlihat di antara x = 1 dan x = 2, jika menggunakan fungsi golden section search ditemukan bahwa nilai x yang memaksimumkan fungsi adalah pada saat x = 1.47