使用遞歸計算Java中曲線y=x的平方與直線x=1的交點

WBOY
發布: 2024-01-09 09:18:46
轉載
1287 人瀏覽過

在java中利用遞歸法計算曲線y x的平方與直線x 1 x軸所包圍的曲邊

public class Util {

public static void main(String[] args) {

System.out.println(getMj(2000));

}

public static double calculateArea(double n){

if(n==1){

return 1.0;

}else{

double r = (n-1) * (n-1) * (n 1) * (2*n 1) / (n * n * n * (2*n-1));

return r*getMj(n-1);

}

}

}

遞歸演算法前提是要了解它的通項公式,2000意味著將曲邊三角形分割成了2000個矩形,具體原理可以參考下圖所示:

在java中利用递归法计算曲线y x的平方与直线x 1

#採用圖1演算法:

an=(n 1)(2n 1) /6n^2

簡單寫法如下:

public class Util {

public static void main(String[] args) {

System.out.println(getMj(100000));

}

public static double calculateArea(double n){

return (n 1)*(2*n 1)/(6*n*n);

}

}

java遞迴問題

(1) 遞歸就是在過程或函數裡呼叫自身;

(2) 在使用遞迴策略時,必須確保有一個明確的遞歸結束條件,也稱為遞迴出口。

遞歸演算法一般用來解決三類問題:

(1)資料的定義是依遞歸定義的。 (Fibonacci函數)

(2)問題解法依遞歸演算法實作。 (回溯)

(3)資料的結構形式是依遞歸定義的。

下面這個例子以遞歸的方法計算n的階乘。

public class Test {

public static int factorial(int n) {

if(n == 0){

return 1;

}else{

return n * factorial(n-1);

}

}

public static void main(String[] args) {

System.out.println(factorial(3));

}

}

java資料結構折半查找的遞歸演算法望高手指點!

package souce;

public class Search {

public static boolean binarySearch(int[] a, int x, int left, int right) { // 二分查找的主方法 // ... }

if (x == a[left] || x == a[right]) { return true; // 找到,回傳 true }

如果(right-left)的結果是負數,則表示右邊的值比左邊的值小。

int mid = (left right)/2; //否則:二分

#if(x == a[mid]) return true; // 找到中間元素,回傳true

else{ //否則

如果x大於中間元素,則傳回二分查找函式(binarySearch)在右半部陣列(a)中繼續找出x,即binarySearch(a,x,mid 1,right)。這樣可以縮小查找範圍,提高查找效率。

else return binarySearch(a, x, left, mid-1); // 如果目標值小於中間元素,在左半部繼續找。

}

}

public static final int[] sort(int[] a) { // 這是一個用於對整數陣列進行排序的方法 // 你可以使用任何排序演算法,例如冒泡排序、插入排序、選擇排序、快速排序等等 // 在這裡,我們使用冒泡排序來對陣列進行排序 for (int i = 0; i a[j 1]) { // 交換元素位置 int temp = a[j];

for (int i = 0; i

for (int j = 0; j

if(a[i]

swap(a,i,j);

}

}

}

return a;

}

private static void swap(int[] a, int i, int j) { //定義一個私人靜態函數swap,用於交換數組a中下標為i和j的元素的位置

int temp = a[i];

a[i] = a[j];

#a[j] = temp;

}

public static void print(int[] a) { //列印函數 for (int i = 0; i

System.out.println();

for (int i = 0; i

System.out.print(a[i]);

if(i!=a.length-1) { System.out.print(","); }

}

System.out.println();

}

public static void main(String[] args) { //測試方法

int[] a = {90, 12, 21, 32, 51, 78, 87, 98};是一個包含8個整數的陣列。

print(sort(a));

System.out.println(binarySearch(sort(a), 40, 0, a.length-1));是用來在已排序數組a中二分查找值為40的元素的程式碼。

}

}

以上是使用遞歸計算Java中曲線y=x的平方與直線x=1的交點的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:docexcel.net
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!