truncate at 10^-3

조회 수: 4 (최근 30일)
diadalina
diadalina 2023년 3월 17일
댓글: Matt J 2023년 3월 17일
i have this code i want to truncate the solution at 10^-3 at each iteraion can anyone help me
t0=0;
y0=1;
tn=1;
h=0.1;
t=[t0:h:tn];
f=@(t,y)(1+t-y)
f = function_handle with value:
@(t,y)(1+t-y)
f1=@(t,y)1
f1 = function_handle with value:
@(t,y)1
f2=@(t,y)-1
f2 = function_handle with value:
@(t,y)-1
n=length(t);
y_t=zeros(1,n);
y_t(1)=y0;
for i=1:n-1
y_t(i+1)=y_t(i)+h*f(t(i),y_t(i))+(h^2/2)*(f1(t(i),y_t(i))+f2(t(i),y_t(i))*f(t(i),y_t(i)));
end

답변 (1개)

Matt J
Matt J 2023년 3월 17일
편집: Matt J 2023년 3월 17일
A few options:
x=round(pi,3)
x = 3.1420
y=floor(pi*1000)/1000
y = 3.1410
sprintf('%.3f',x)
ans = '3.142'
sprintf('%.3f',y)
ans = '3.141'
  댓글 수: 4
diadalina
diadalina 2023년 3월 17일
편집: Matt J 2023년 3월 17일
i'm trying fo truncate at 10^3 y-tt is the trancted vector y-t is the vector without truncation but they are different i can't find where the problem
n=length(t);
y_tt=zeros(1,n);
y_tt(1)=fix(y0*10^3)/10^3;
for i=1:n-1
%y_tt(i)=fix(y_tt(i)*10^3)/10^3;
y_tt(i+1)=y_tt(i)+h*f(t(i),y_tt(i))+(fix(h^2/2*10^3)/10^3)*(f1(t(i),y_tt(i))+f2(t(i),y_tt(i))*f(t(i),y_tt(i)));
y_tt(i)=fix(y_tt(i+1)*10^3)/10^3;
end
y_t=zeros(1,n);
y_t(1)=y0;
for i=1:n-1
y_t(i+1)=y_t(i)+h*f(t(i),y_t(i))+h^2/2*(f1(t(i),y_t(i))+f2(t(i),y_t(i))*f(t(i),y_t(i)))
end
M=[y_tt',y_t']
this what matlab gives to me they are differents :
M =
1.004 1
1.019 1.005
1.041 1.019
1.07 1.0412
1.107 1.0708
1.149 1.1071
1.197 1.1494
1.249 1.1972
1.307 1.25
1.368 1.3072
1.3685 1.3685
can you help me please , i shoud find the same 3 firsts dicimals in y_tt and y_t
Matt J
Matt J 2023년 3월 17일
I imagine you would want to do this:
y_t(1)=y0;
for i=1:n-1
y_t(i+1)=y_t(i)+h*f(t(i),y_t(i))+h^2/2*(f1(t(i),y_t(i))+f2(t(i),y_t(i))*f(t(i),y_t(i)))
end
y_tt=fix(y_t*1e3)/1e3;
M=[y_tt',y_t']

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by