Posts Tagged ‘float’

Parse floating point numbers from a string in ruby

Monday, April 11th, 2016

Given a string like "v 1.2 4.2342 8.2 -1.0e14" (e.g., from a .obj file), you could use the following ruby line to extract an ordered list of the contained floating point numbers:

line.scan(/[+-]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?/).collect{|s| s.to_f}

which would produce

=> [1.2, 4.2342, 8.2, 100000000000000.0]

Casting bug in g++ llvm 4.2 int to double

Monday, July 2nd, 2012

The following code seems to compile incorrectly using g++, llvm version 4.3 with -O3:


#include <iostream>

int main(int argc,char * argv[])
{
  using namespace std;
  // loop over canonical view quaternions
  for(int sign = -1;sign<=1;sign+=2)
  {
    std::cout<<sign<<" --> "<<(double)sign<<std::endl;
    // Necessary to reproduce bug
    for(int i = 0; i<1; i++)
    {
      for(int j = 0;j<1;j++)
      {
      }
    }
  }
  return 0;
}

For some reason it is not casting the int, rather it seems to be just reinterpreting the bits as a double.

Switching off compile optimization, switching to plain old g++ or switching to float instead of double works, but are not helpful in my case. Instead I did something that works, but is likely non-optimal, I replaced the double cast with a float cast followed by a double cast.


(double)(float)sign

Getting python to print 5 digits of accuracy in the current time in seconds

Monday, January 11th, 2010

In the python shell if I type:


import time
time.time()

I get the current time in seconds with 5 digits past the decimal place of accuracy:


1263245893.382139

If I want to use this as a unique ID then I need to have this value as a string. Namely I need to be able to print it. But if I issue:


print time.time()

I only get 2 digits of accuracy past the decimal place:


1263245893.38

This seems to be because print when converting the time to a string is rounding its float value someplace. To solve this I use instead:


print "%f" %  time.time()

Which again returns all of the accuracy places I original had:


1263245893.382139

Finally to save this value as a string I just remove the print and instead have a variable on the left hand side of an equals sign:


current_time = "%f" %  time.time()

Rounding floats to ints with bc in bash

Sunday, August 16th, 2009

I’ve seen a lot of bizarre attempts to round floating point numbers to integers in bash. Here’s my cheap hack using bc:


echo "($float+0.5)/1" | bc 

If your floating point number is in a variable called float then this will round up or down accordingly. As in 1.0 and 1.4 round to 1, while 1.5 and 1.9 round to 2.