Calcite | Level 5

Can I use do loop to calculation pi?

I   fi       pi(=( f(i)+f(i-1) ) /2 )

1  0.263    (0.263+0)/2                (f(0)=0)

2  0.263    (0.263+0.263)/2

3  0.91     (0.91+0.263)/2

4  0.12     (0.12+0.91)/2

5  0.12     (0.12+0.12)/2

Can I use do loop or other method to calculation pi?

Thanks!

4 REPLIES 4
Amethyst | Level 16

Re: Can I use do loop to calculation pi?

I believe you can achieve the same result without the do loop if you prefer it this way

``````data have;
input f;
cards;
0.263
0.263
0.91
0.12
0.12
;

data want;
set have;
pi=((f+coalesce(lag(f),0))/2);
run;``````
Thanks,
Jag
Meteorite | Level 14

Re: Can I use do loop to calculation pi?

You can use the LAG() function to retrieve the previous value of fi.

The SUM() function is better than the "+" operator in your case as it ignores missing values. So it can easily handle the calculation at the first row, where lag(i) is not defined.

Best,

``````data want;
set have;
pi = sum(fi,lag(fi))/2;
run;``````
Super User

Re: Can I use do loop to calculation pi?

@yuwentaiwan wrote:

I   fi       pi(=( f(i)+f(i-1) ) /2 )

1  0.263    (0.263+0)/2                (f(0)=0)

2  0.263    (0.263+0.263)/2

3  0.91     (0.91+0.263)/2

4  0.12     (0.12+0.91)/2

5  0.12     (0.12+0.12)/2

Can I use do loop or other method to calculation pi?

Thanks!

Is this a programming exercise or do you want to USE the value of pi?

If you need to use pi then you would use the function CONSTANT with 'pi' as the argument.

```data junk;
x=constant('pi');
put x best16.;
run;```
Barite | Level 11

Re: Can I use do loop to calculation pi?

You can use Proc DS2 or FCMP to compute via recursion.

Or try Proc FCMP SOLVE() function

Discussion stats
• 4 replies
• 583 views
• 3 likes
• 5 in conversation