From mboxrd@z Thu Jan 1 00:00:00 1970 X-Spam-Checker-Version: SpamAssassin 3.4.4 (2020-01-24) on polar.synack.me X-Spam-Level: X-Spam-Status: No, score=-0.9 required=5.0 tests=BAYES_00,FROM_NUMERIC_TLD autolearn=no autolearn_force=no version=3.4.4 X-Google-Thread: a07f3367d7,fa37ee962bc4b00d X-Google-Attributes: gida07f3367d7,public,usenet X-Google-NewGroupId: yes X-Google-Language: ENGLISH,ASCII-7-bit Path: g2news2.google.com!news3.google.com!feeder.news-service.com!tudelft.nl!txtfeed1.tudelft.nl!zen.net.uk!dedekind.zen.co.uk!news-peer-lilac.gradwell.net!not-for-mail From: "Stuart" Newsgroups: comp.lang.ada References: <4a12ffa3$0$2853$ba620e4c@news.skynet.be> <4a13baef$1_1@glkas0286.greenlnk.net> Subject: Re: Conversion from floating point to signed 16 bits Date: Wed, 20 May 2009 09:48:34 +0100 X-Priority: 3 X-MSMail-Priority: Normal X-Newsreader: Microsoft Outlook Express 6.00.2900.3138 X-RFC2646: Format=Flowed; Response X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2900.3350 Message-ID: <4a13bf49$1_1@glkas0286.greenlnk.net> X-Original-NNTP-Posting-Host: glkas0286.greenlnk.net NNTP-Posting-Host: 20.133.0.1 X-Trace: 1242809316 news.gradwell.net 512 dnews/20.133.0.1:44903 X-Complaints-To: news-abuse@gradwell.net Xref: g2news2.google.com comp.lang.ada:5954 Date: 2009-05-20T09:48:34+01:00 List-Id: "Stuart" wrote in message news:4a13baef$1_1@glkas0286.greenlnk.net... > "Olivier Scalbert" wrote in message > news:4a12ffa3$0$2853$ba620e4c@news.skynet.be... >> My problem: >> I need to convert an "analogic" value which can vary from 0.0 to 1.0 into >> a "discrete" value which is a signed 16 bits integer. ... >> with Ada.Text_IO; >> >> procedure convert is >> type Analog_Value is digits 10 range 0.0 .. 1.0; >> type Signed_16 is range -32768 .. 32767; ... >> begin ... >> Put(Cv(0.50)); -- Must be 0 ... >> end convert; > Extending your [reasonable] assumptions about the base type of > Analog_Value you could dispense with the Unsigned_16 altogether: > > function Cv(Value: Analog_Value) return Signed_16 is > begin > return Signed_16(65535.0*Value - 32768.0); > end Cv; Ooops! Unfortunately, due to Ada rounding rules this fails your requirement for Cv(0.50) as it returns -1. In my defence I plead that we got very annoyed by the overhead of Ada rounding in a similar scenario that we rigged our conversions and don't see this problem. You can might also weedle your way around the effect of the rounding by trying something like: function Cv(Value: Analog_Value) return Signed_16 is begin return Signed_16(65535.0*Value - 32767.9999); end Cv; You could probably _derive_ a value to replace -32768.0 by consideration of the rounding effect over the range of inputs 0.0 .. 1.0. Regards Stuart