编写程序:计算π的近似值,π的计算公式为

编写程序:计算π的近似值,π的计算公式为,第1张

#include<stdio.h>

main()

{ int n,idouble t,

sum/*1*/

printf("请输入n的值\n")

scanf("%d",&n)

sum=2i=1t=2/*2*/

while(i<n) { t=t*(2*i)*(2*i)/(2*i-1)/(2*i+1)

/*3*/ // sum=sum*ti=i+1}

printf("π的值=%f\n",t)/*4*/ }

或。

写一个Java程序来实现蒙特卡洛法求π的近似值

import java.io.BufferedReader

import java.io.InputStreamReader

public class MonteCarloPi {

public static void main(String[] args) throws Exception{

BufferedReader br = new BufferedReader(new InputStreamReader(System.in))

System.out.print("How many darts shoud I toss at the board?\n")

String s = br.readLine()

int numberOfDarts = Integer.parseInt(s.trim())

double radius = 1.0

Dartboard d = new Dartboard(radius)

for(int i=1i<=numberOfDartsi++){

Toss t = Toss.getRandom(radius)

d.strike(t)

}

double fractionIn = d.getFractionIn()

double pi = 4.0 * fractionIn

System.out.println("Pi is approximately "+pi)

}

}

class Dartboard{

private double radius

private int insideCircle, outsideCircle

public Dartboard(double radius){

this.radius = radius

insideCircle = 0

outsideCircle = 0

}

public void strike(Toss toss){

double x = toss.getX()

double y = toss.getY()

if(Math.sqrt(x*x + y*y) <radius)

insideCircle++

else

outsideCircle++

}

public double getFractionIn() {

double total = (double) (insideCircle + outsideCircle)

return (double) insideCircle/total

}

}

class Toss{

private double x,y

public Toss(double x, double y){

this.x = x

this.y = y

}

public double getX(){return x}

public double getY(){return y}

public static Toss getRandom(double radius){

double x,y

double size = Math.random()

double sign = Math.random()

size = size * radius

if(sign >0.5)

x = size

else

x = -size

size = Math.random()

sign = Math.random()

size = size * radius

if(sign >0.5)

y = size

else

y = -size

return new Toss(x,y)

}

}

扩展资料:

C语言:用循环结构分别编写程序

#include

void main()

{

\x09int n=1

\x09float temp

\x09float sum=0

\x09do

\x09{

\x09\x09temp=(float)1/(2*n-1)

\x09\x09if(n%2==1)

\x09\x09\x09sum+=temp

\x09\x09else

\x09\x09\x09sum-=temp

\x09\x09n++

\x09}while(temp>=0.000001)

\x09printf("Pi=%f\n",sum*4)

}

#include <stdio.h>

int main()

{

    double pi

    unsigned long i,n

    scanf("%lu",&n)

    for(pi=1,i=1i<=n++i)

    {

        pi*=(i+1)/2*2.0 / ( (i+1)/2*2+(i-1)%2*2-1 )

    }

    printf("pi=%.10lf\n",pi*=2)

    return 0

}

要求:误差小于0.00001

Private Sub Command1_Click()

Dim i%, n&, t!, e!

e = 2

i = 1

t = 1

Do While t >0.00001

i = i + 1

t = t / i

e = e + t

Loop

Print "计算了"; i; "项目和是:"; e

Print Exp(1) ‘与上句输出值进行对比以证明算法的正确性

End Sub

这种算法是有问题的,不能达到指定的精度的!t <= 0.00001 时结束了循环,这个只是到这一项为止,该项的值比精度小,但是不能保证被舍掉的后面部分(无穷项之和)阶乘的倒数之和比指定的精度小!


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/11074056.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-13
下一篇 2023-05-13

发表评论

登录后才能评论

评论列表(0条)

保存