如何計算 \(1+2+3+\cdots+10,000\) 的結果? 拜科技之賜,這個問題的答案上網就可以查得到了。

也可以用公式來處理: \[1+2+\cdots+n=\frac{n(n+1)}{2} \Rightarrow 1+2+3+\cdots+10,000 = \frac{10,000 \cdot (10,001)}{2} = 50,005,000\]

不過問題稍微變化一下,就沒那麼容易,也不容易找到公式了: \[51^{0.5}+52^{0.5}+\cdots+555^{0.5} = ?\] 以下用 R 的簡單迴圈來進行上式的計算:

total <- 0
for (i in 51:555){total <- total + i^0.5}
cat("加總結果為", total)
## 加總結果為 8489.159

善用 seq 寫法,也可避開迴圈:

x <- seq(51, 555)
total <- sum(x^0.5)
cat("加總結果為", total)
## 加總結果為 8489.159

或是用 Python :

library(reticulate)
## Warning: package 'reticulate' was built under R version 4.5.1
use_python('C:\\Users\\peter\\AppData\\Local\\Programs\\Python\\Python313')

載入套件後可執行以下 Python 程式碼:

total = 0
for i in range(51,556): 
    total = total + i**0.5
print(total)
## 8489.15935296073

也可以控制印出每一次加總的結果 (以下僅列出前十項,即 \(\sqrt{51}+\sqrt{52}+\cdots+\sqrt{60}\))

total <- 0
for (i in 51:60){total <- total + i^0.5 ; print(total)}
## [1] 7.141428
## [1] 14.35253
## [1] 21.63264
## [1] 28.98111
## [1] 36.39731
## [1] 43.88062
## [1] 51.43046
## [1] 59.04623
## [1] 66.72738
## [1] 74.47334

catprint 指令更有彈性之處的在於可以將字串與變數並呈。

使用 seq 指令,配合 for 迴圈記錄一項項加總的累積過程:

options(digits=15)  #增加有效位數至15位
sum <- 0
x <- c(51:60)
for (i in 51:60){sum <- sum + x[i-50]^0.5 ; cat("累積到 i=",i,"sum=",sum,"\n")}
## 累積到 i= 51 sum= 7.14142842854285 
## 累積到 i= 52 sum= 14.3525309794708 
## 累積到 i= 53 sum= 21.6326408687513 
## 累積到 i= 54 sum= 28.9811100971009 
## 累積到 i= 55 sum= 36.3973085841965 
## 累積到 i= 56 sum= 43.8806233577444 
## 累積到 i= 57 sum= 51.4304577930152 
## 累積到 i= 58 sum= 59.0462308988791 
## 累積到 i= 59 sum= 66.7273766467477 
## 累積到 i= 60 sum= 74.4733433391625

Python 作法:

total = 0
for i in range(51,61):
    total = total + i**0.5
    print("累積至第 %d 項的總合為 %f" %(i-50,total))
## 累積至第 1 項的總合為 7.141428
## 累積至第 2 項的總合為 14.352531
## 累積至第 3 項的總合為 21.632641
## 累積至第 4 項的總合為 28.981110
## 累積至第 5 項的總合為 36.397309
## 累積至第 6 項的總合為 43.880623
## 累積至第 7 項的總合為 51.430458
## 累積至第 8 項的總合為 59.046231
## 累積至第 9 項的總合為 66.727377
## 累積至第 10 項的總合為 74.473343
    
print("全部的總合為 %f" %(total))
## 全部的總合為 74.473343

考慮以下變化:

\[2^{0.3}+4^{0.3}+6^{0.3}+\cdots+198^{0.3} = ?\] \[2^{0.3}+4^{0.6}+6^{0.9}+\cdots+198^{29.7} = ?\]

參考提示分別為:

options(digits=15)
total <- 0
for (i in 1:99){total <- total + (2*i)^0.3}
cat("加總結果為", total)
## 加總結果為 374.209953395939

以及

total <- 0
for (i in 1:99){total <- total + (2*i)^(0.3*i)}
cat("加總結果為", total)
## 加總結果為 1.91654366141522e+68

請注意我們用了指令 options(digits=15) 控制結果的有效位數。