How to stop rounding values when i use array?

341 次查看(过去 30 天)
Hello everyone,
clear; clc;
syms f(y,t); %sym func
h = 0.1; %step size
ti = 0; %initial value
yi = 1; %value at ti = 0
f(t,y) = (1+2*t)*sqrt(y); %dif equation
for ti=[0:h:0.9] % t[0,1] condition with step size
k1 = f(ti,yi); %formula
k2 = vpa(f(ti+((1/2)*h),yi+((1/2)*k1*h))); %formula
k3 = vpa(f(ti+((1/2)*h),yi+((1/2)*k2*h))); %formula
k4 = vpa(f(ti+h,yi+k3*h)); %formula
c = ti+h; %trying to make it equal to another step
c = yi + ((1/6)*(k1 + 2*k2 + 2*k3 +k4)*h); %formula
ti = ti+h; % for calculating one step forward
yi = c %my values
end
This is my code. When i run this code i get these values which is alright for me.
yi = 1.113024864238065836914069386071
yi = 1.2543996857913360546038612123358
yi = 1.4280244537263716534345718377563
yi = 1.6383991563454554525623395070174
yi = 1.8906237821755359512988676861658
yi = 2.1903983207422986759010819641543
yi = 2.5440227630548922996833947540414
yi = 2.9583971018166219626153507261848
yi = 3.4410213314236507023824643153582
yi = 3.9999954478254578455556866889108
But when i use an array to plot these values. It automatically rounds them to closest value which is not alright for me cuz i need to plot the error as well. How can i solve this
Code with array:
clear; clc;
syms f(y,t); %sym func
h = 0.1; %step size
ti = 0; %initial value
yi = 1; %value at ti = 0
f(t,y) = (1+2*t)*sqrt(y); %dif equation
a = [];
b = 1;
for ti=[0:h:0.9] % t[0,1] condition with step size
k1 = f(ti,yi); %formula
k2 = vpa(f(ti+((1/2)*h),yi+((1/2)*k1*h))); %formula
k3 = vpa(f(ti+((1/2)*h),yi+((1/2)*k2*h))); %formula
k4 = vpa(f(ti+h,yi+k3*h)); %formula
c = ti+h; %trying to make it equal to another step
c = yi + ((1/6)*(k1 + 2*k2 + 2*k3 +k4)*h); %formula
ti = ti+h; % for calculating one step forward
yi = c %my values
a(b)=c
b = b+1;
end
plot(a,"r*")
a = 1.1130 1.2544 1.4280 1.6384 1.8906 2.1904 2.5440 2.9584 3.4410 4.0000
i know it is not a big problem one of them is 3.99999 other one is 4.0000 but i would like to know how to solve this.

采纳的回答

Cris LaPierre
Cris LaPierre 2021-4-7
By default, MATLAB only displays 4 decimal places. This does not change the actual value. It's just for display. You can modify the display format using the format function.
a = 1.113024864238066
a = 1.1130
format long
a
a =
1.113024864238066

更多回答(2 个)

David Hill
David Hill 2021-4-7
The values in your array (a) are not rounded, they are only rounded in the display of them. To see the actual values, change format to long.
display(a);
format long;
display(a);

Maria Elena
Maria Elena 2023-10-25
no rounding

类别

Help CenterFile Exchange 中查找有关 Number Theory 的更多信息

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by