0

I'm following along a series of youtube lectures on modern C++ by Igor Bogoslavskyi. In CPP-06 he's shown how floating point numbers are represented internally i.e. sign bit, magnitude and mantissa. In the homework he asks to implement the following:

int CountSameSignificantDigits(double a, double b); This function should count how many significant digits are there between the two numbers. Only count the number of significat digits up to 100, so that the function returns 100 if the numbers are equal.

It does not make sense to me how he wants the count of up to 100 significant digits. What if the two same doubles have less than 100 significant digits? My current idea is to simply convert these values to strings and iterate over them, but I'm not confident this is a good solution, and even then I'm not sure how to deal with aformentioned ambiguity. Any thoughts?

Robert Dodier
  • 16,905
  • 2
  • 31
  • 48
Vocaloidas
  • 360
  • 2
  • 17
  • Answer related to question: https://stackoverflow.com/a/50970282/4641116 – Eljay Oct 03 '20 at 16:03
  • I'll agree that the homework problem could be worded better. Did the YouTube videos go through an editorial review process similar to what textbooks are traditionally subject to? – JaMiT Oct 03 '20 at 16:08
  • @JaMiT He only showed how precision loss can occur and moved on to the next topic unfortunately. Usually the homework reflects the lecture material, but I seriously struggle to understand how he expects this to be implemented given his content. To actually answer your question; i don't really know. I downloaded the homework from http://www.ipb.uni-bonn.de/teaching/modern-cpp/ (week 4). It could very well be that he reviewed it and corrected it for the enrolled students. – Vocaloidas Oct 03 '20 at 16:10
  • I dunno, this business about counting only up to 100 doesn't make sense -- why stop at 100? Assuming finite precision, it could be greater than 100 but it is not unlimited, so why not count all the digits. Also, return 100 if the numbers are the same? What? ... Anyway, aside from that, how about looking at abs(b - a) and then comparing that to a or b -- if a and b are nearly the same, the magnitude of abs(b - a) is smaller than either one; maybe something like log10(a) - log10(abs(b - a)) is relevant. I assume you can filter out cases where a and b are very different and return 0 for those. – Robert Dodier Oct 03 '20 at 20:13
  • Adding to the confusion is that converting a double to a decimal representation (in a string for instance) is not trivial. And C++ imposes no requirements that it be done accurately by the standard library. So this is a seriously advanced task. – john Oct 03 '20 at 20:27

1 Answers1

0

You can use to_string() function from the <string> header to convert given number and after that, you can access the individual digits using indexing for comparision like:
string a="hello" Then a[0] is 'h'.

DS__ggg
  • 13
  • 4