How can I set x=1.1 with 30 decimal precision?

10 vues (au cours des 30 derniers jours)
Elisabeth
Elisabeth le 24 Nov 2019
Commenté : Guillaume le 24 Nov 2019
Hi all!
I am trying to understand a bit better how decimal precision works.
I want to define and work with 30 decimals, I know that is not usually necessary, but I would like to understand the following better.
So, if I set x=1 and use vpa(x,30), I get:
1.000000000000000000000000000000
However, if I do the same with x=1.1, I get:
1.100000000000000088817841970013
My question is, if I want to work with 1.1 with 30 digit precision, but my initial number is already not exactly what I want... how can I do that then? Is it possible to do it? What's the reason behind that? I know it might be a basic concept or question, but I don't see how to do it.
Thank you in advance!

Réponses (1)

Guillaume
Guillaume le 24 Nov 2019
When you do
x = 1.1
You create an x of class double. double numbers have a decimal precision of around 16 significant digits. Most numbers cannot be stored exactly as double so the actual number stored is not exactly the same as the textual representation that you wrote.
This is the case for 1.1 which cannot be stored exactly as double. The nearest value that can be stored is 1.100000000000000088817841970012523233890533447265625. For display matlab (and other languages) round that to 1.1 as it assumes that's what you meant. To learn more about how double are stored search for IEE754 (e.g. wikipedia)
So, when you pass x to vpa, that's the number that is actually passed and since you ask vpa to show you 30 digits, it shows you the first 30 digits.
If you want 1.1 exactly, you need to pass its textual representation to vpa.
vpa('1.1')
  2 commentaires
Elisabeth
Elisabeth le 24 Nov 2019
Thank you for your response!
So, if I want 1.1 exactly, and I pass its textual representation to vpa, then it means that I'm using the number 1.10000000000000000000000000? When I try to print it, it still shows 1.1000000000000000888178419700125232339.
My point is that I want to start my code by using 1.10000000000000000000000000 as initial x0, to obtain x1,x2 and x3 (Newton-Raphson iterative method) with 30 decimal precision. Everything works fine, but the decimals I'm getting at the end are not exactly what I should be getting due to that fact.
Guillaume
Guillaume le 24 Nov 2019
"When I try to print it, it still shows [...]"
Oh! I don't have the symbolic toolbox so I assumed that's how it works. I believe the following should work correctly then:
vpa(sym('1.1'))

Connectez-vous pour commenter.

Community Treasure Hunt

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

Start Hunting!

Translated by