Convertion from Speed to (Speed)^-1

user1864070 :

Using the javax.measure library, I try to convert km/h in min/km.

However min/km is not a part of the units proposed by the unit-ri.

So i tried to create my own unit: MINUTE_BY_KILOMETERS

import javax.measure.Quantity;
import javax.measure.Unit;
import javax.measure.quantity.Length;
import javax.measure.quantity.Speed;

import tec.units.ri.quantity.Quantities;
import tec.units.ri.unit.MetricPrefix;
import tec.units.ri.unit.Units;
    Quantity<Speed> speed = Quantities.getQuantity(10, Units.KILOMETRE_PER_HOUR);
    assertEquals("10 km/h", speed.toString());

    // Conversion m/s
    assertEquals("2.7777800000000004 m/s", speed.to(Units.METRE_PER_SECOND).toString());

    // Conversion min/km
    Unit<Speed> MINUTE_BY_KILOMETERS = Units.MINUTE.divide(MetricPrefix.KILO(Units.METRE)).asType(Speed.class);
    assertEquals("6 min/km", speed.to(MINUTE_BY_KILOMETERS).toString());

But I get an exception:

java.lang.ClassCastException: The unit: min/km is not compatible with quantities of type interface javax.measure.quantity.Speed
    at tec.units.ri.AbstractUnit.asType(AbstractUnit.java:274)

I suppose I have to create my own Type but I didn't find out how.

Can somebody provide an example please?

user1864070 :

I finally found out there was an .inverse function in order to do the conversion when needed.

So you have to keep the (distance / time) metrics in the code to do all the operations and conversions, and add a .inverse() at the end when you want your value:

Unit<Speed> KILOMETERS_BY_MINUTES = MetricPrefix.KILO(Units.METRE).divide(Units.MINUTE).asType(Speed.class);
assertEquals("5.9999952000038395 min/km", speed.to(KILOMETERS_BY_MINUTES).inverse().toString());

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=149790&siteId=1